Compare commits

..

62 Commits

Author SHA1 Message Date
Sebastian 6368ede9fa chore(deps): update dependency phpunit/phpunit to v12.5.34
JS Unit Tests / test (pull_request) Successful in 25s
Build Test / build (pull_request) Successful in 27s
PHP Integration Tests / Integration Tests (pull_request) Failing after 1m14s
PHP Unit Tests / test (pull_request) Successful in 1m24s
2026-08-31 03:02:58 +00:00
Sebastian a0093c9547 feat: implement 3 variants
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-29 19:10:48 -04:00
Sebastian f39ad1804d feat: implement preview manager
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-29 18:42:30 -04:00
Sebastian eaea5f4c83 feat: implement preview configuration
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-29 07:53:14 -04:00
Sebastian 30a8eddf06 feat(preview): add shared preview provider contracts
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-28 23:51:29 -04:00
Sebastian 96fbdbab90 feat(core): add system store write conflict handling
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-28 23:28:06 -04:00
Sebastian 545a776aeb feat(core): add CLI management for tenant system stores
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-28 20:56:17 -04:00
Sebastian e137de1183 feat(core): implement tenant-scoped system store manager
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-28 20:47:27 -04:00
Sebastian a1413db12f feat(core): add tenant system store contracts and configuration
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-28 20:39:00 -04:00
Sebastian f0598412f3 feat(core): add system store service interface
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-28 20:25:58 -04:00
Sebastian 52166feca2 refactor(core): centralize reserved system user identity
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-28 19:36:43 -04:00
Sebastian 964128e051 docs: document entityModify()'s authoritative-identifier contract
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-25 22:46:29 -04:00
Sebastian b3e0c00c87 feat: collapse system menu by default
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-09 23:18:39 -04:00
Sebastian 4f5ea8c442 fix: only sxhow menu section when there are items
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-09 23:12:47 -04:00
Sebastian a4c467d54e fix: remove dead code
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-09 23:03:27 -04:00
Sebastian f24e0ae669 fix: user name size
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-09 23:00:52 -04:00
Sebastian 673bdc1f7a feat: remove user name
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-09 22:50:20 -04:00
Sebastian 71ddd3442f fix: improve secret input
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-08 22:39:48 -04:00
Sebastian 0dd735045d fix: remove extra password labek
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-08 22:30:20 -04:00
Sebastian 5646591c74 fix: auth icons
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-08 22:26:47 -04:00
Sebastian a5acea72c3 fix: allow any login name not just email
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-08 22:22:43 -04:00
Sebastian 62b416f13e refactor: base event
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-08 22:15:24 -04:00
Sebastian c8e6efe203 feat: improve deferred event processing
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-08 00:20:32 -04:00
Sebastian f147ffc5c7 feat: introduce user management events
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-07 22:32:45 -04:00
Sebastian 985e4a6450 fix: find npm path
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-07 00:46:36 -04:00
Sebastian b14bd302a3 fix(security): emit authentication success events
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-06 00:08:58 -04:00
Sebastian 5b3e8f6588 fix(events): close deferred scope after listener failure
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-06 00:02:15 -04:00
Sebastian 84eb0e2c21 refactor(security): replace generic event with severity enum
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-05 23:59:49 -04:00
Sebastian 3f9c2500d9 refactor(security): type firewall policy events
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-05 23:56:28 -04:00
Sebastian 2494cef02f refactor(security): type firewall rule lifecycle events
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-05 23:51:40 -04:00
Sebastian a5be782c51 refactor(security): add typed authentication-success event
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-05 23:42:24 -04:00
Sebastian f4df769b3c refactor(security): add typed suspicious-activity event
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-05 23:38:59 -04:00
Sebastian 688afbe5a1 refactor(security): add typed rate-limit event
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-05 23:36:44 -04:00
Sebastian 7c2a8dfbd3 refactor(security): add typed access-denied event
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-05 23:34:05 -04:00
Sebastian e223ae7543 refactor(security): add typed brute-force detection event
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-05 23:31:13 -04:00
Sebastian a8e29d0305 feat(security): emit authentication failures for firewall handling
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-05 23:26:01 -04:00
Sebastian a363a1a4bc refactor: use consistant naming
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-05 23:17:04 -04:00
Sebastian 5c65c8592c feat: Introduce typed authentication failure event
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-05 22:50:38 -04:00
Sebastian 52afd35d6f feat: make event state constructor-only and immutable
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-05 22:46:33 -04:00
Sebastian ba4deccea9 feat: Remove unused event serialization
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-05 22:21:04 -04:00
Sebastian 2012d67be7 fix: Enforce security event severity defaults
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-05 22:17:04 -04:00
Sebastian 649fa47c68 feat: Move security events into core
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-05 22:14:22 -04:00
Sebastian a73ca3abd6 feat: Move event runtime implementation into core
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-05 22:09:53 -04:00
Sebastian 01ed0f3080 feat: Introduce event listener registration contract
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-05 22:04:26 -04:00
Sebastian fb39aa57fd feat(firewall): add audited configuration management
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-03 22:44:34 -04:00
Sebastian d5ca89e160 feat(firewall): add audited rule lifecycle management
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-03 22:35:45 -04:00
Sebastian b06c18d38e feat(firewall): add safeguarded rule creation
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-03 22:27:20 -04:00
Sebastian 6700ff145d feat(firewall): add operational status reads
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-03 22:22:07 -04:00
Sebastian d919b70a2e feat(firewall): add scoped log administration reads
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-03 22:17:13 -04:00
Sebastian 74696bbeb3 feat(firewall): add scoped rule administration reads
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-03 22:05:00 -04:00
Sebastian 4ee91a7918 feat(firewall): complete operational reliability phase
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-30 23:39:37 -04:00
Sebastian 90d847ffae perf(firewall): use BSON dates and add query indexes
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-30 23:13:37 -04:00
Sebastian ad6443bff3 fix(firewall): serialize automatic brute-force blocking
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-30 23:05:32 -04:00
Sebastian a5c10e9b9b fix(firewall): account for authentication failures exactly once
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-30 23:01:38 -04:00
Sebastian 7aa8a27b1b feat(firewall): audit rule lifecycle changes
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-30 22:57:25 -04:00
Sebastian 5ada4c0c45 fix(firewall): register missing security audit events
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-30 22:50:42 -04:00
Sebastian 12037da367 feat(firewall): complete rule-match audit context
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-30 22:46:27 -04:00
Sebastian abc5bfcccc fix(firewall): enforce system rules independently of tenant context
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-30 22:41:27 -04:00
Sebastian da81f1ddf1 refactor(firewall): separate enforcement from rule management
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-30 22:35:24 -04:00
Sebastian 266b364c93 fix(firewall): preserve tenant ownership for automatic blocks
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-30 22:11:27 -04:00
Sebastian 3b9a5cd5ab feat(firewall): validate rules and add typed configuration
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-30 21:54:23 -04:00
Sebastian 63d91ca7fa feat(firewall): add tenant and system rule scopes
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-30 21:38:19 -04:00
148 changed files with 11087 additions and 1093 deletions
Generated
+46 -34
View File
@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "d162d02532b7705788ced1ea4c360c05",
"content-hash": "3d12a8375788867d9c596cd5ae05a185",
"packages": [
{
"name": "laravel/serializable-closure",
@@ -1366,20 +1366,20 @@
"packages-dev": [
{
"name": "myclabs/deep-copy",
"version": "1.13.4",
"version": "1.14.0",
"source": {
"type": "git",
"url": "https://github.com/myclabs/DeepCopy.git",
"reference": "07d290f0c47959fd5eed98c95ee5602db07e0b6a"
"reference": "8680aa248f8e07bc8fb43f56f0f5fc77a0c96aae"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/07d290f0c47959fd5eed98c95ee5602db07e0b6a",
"reference": "07d290f0c47959fd5eed98c95ee5602db07e0b6a",
"url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/8680aa248f8e07bc8fb43f56f0f5fc77a0c96aae",
"reference": "8680aa248f8e07bc8fb43f56f0f5fc77a0c96aae",
"shasum": ""
},
"require": {
"php": "^7.1 || ^8.0"
"php": "^8.0"
},
"conflict": {
"doctrine/collections": "<1.6.8",
@@ -1414,15 +1414,15 @@
],
"support": {
"issues": "https://github.com/myclabs/DeepCopy/issues",
"source": "https://github.com/myclabs/DeepCopy/tree/1.13.4"
"source": "https://github.com/myclabs/DeepCopy/tree/1.14.0"
},
"funding": [
{
"url": "https://tidelift.com/funding/github/packagist/myclabs/deep-copy",
"type": "tidelift"
"url": "https://github.com/mnapoli",
"type": "github"
}
],
"time": "2025-08-01T08:46:24+00:00"
"time": "2026-08-11T10:17:44+00:00"
},
{
"name": "nikic/php-parser",
@@ -1689,23 +1689,23 @@
},
{
"name": "phpunit/php-file-iterator",
"version": "6.0.1",
"version": "6.0.2",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/php-file-iterator.git",
"reference": "3d1cd096ef6bea4bf2762ba586e35dbd317cbfd5"
"reference": "a248d1640ab059b075f53a2ef0f9856e864e06b5"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/3d1cd096ef6bea4bf2762ba586e35dbd317cbfd5",
"reference": "3d1cd096ef6bea4bf2762ba586e35dbd317cbfd5",
"url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/a248d1640ab059b075f53a2ef0f9856e864e06b5",
"reference": "a248d1640ab059b075f53a2ef0f9856e864e06b5",
"shasum": ""
},
"require": {
"php": ">=8.3"
},
"require-dev": {
"phpunit/phpunit": "^12.0"
"phpunit/phpunit": "^12.5.33"
},
"type": "library",
"extra": {
@@ -1738,7 +1738,7 @@
"support": {
"issues": "https://github.com/sebastianbergmann/php-file-iterator/issues",
"security": "https://github.com/sebastianbergmann/php-file-iterator/security/policy",
"source": "https://github.com/sebastianbergmann/php-file-iterator/tree/6.0.1"
"source": "https://github.com/sebastianbergmann/php-file-iterator/tree/6.0.2"
},
"funding": [
{
@@ -1758,7 +1758,7 @@
"type": "tidelift"
}
],
"time": "2026-02-02T14:04:18+00:00"
"time": "2026-08-25T14:40:53+00:00"
},
{
"name": "phpunit/php-invoker",
@@ -1946,16 +1946,16 @@
},
{
"name": "phpunit/phpunit",
"version": "12.5.33",
"version": "12.5.34",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/phpunit.git",
"reference": "b98e028a26c5c5ba7e4a54be96ccf35f2914d184"
"reference": "6cbff63d670de92cb1cb3d2ff9f40327e9da9c7f"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/b98e028a26c5c5ba7e4a54be96ccf35f2914d184",
"reference": "b98e028a26c5c5ba7e4a54be96ccf35f2914d184",
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/6cbff63d670de92cb1cb3d2ff9f40327e9da9c7f",
"reference": "6cbff63d670de92cb1cb3d2ff9f40327e9da9c7f",
"shasum": ""
},
"require": {
@@ -1965,18 +1965,18 @@
"ext-libxml": "*",
"ext-mbstring": "*",
"ext-xmlwriter": "*",
"myclabs/deep-copy": "^1.13.4",
"myclabs/deep-copy": "^1.14.0",
"phar-io/manifest": "^2.0.4",
"phar-io/version": "^3.2.1",
"php": ">=8.3",
"phpunit/php-code-coverage": "^12.5.7",
"phpunit/php-file-iterator": "^6.0.1",
"phpunit/php-file-iterator": "^6.0.2",
"phpunit/php-invoker": "^6.0.0",
"phpunit/php-text-template": "^5.0.0",
"phpunit/php-timer": "^8.0.0",
"sebastian/cli-parser": "^4.2.1",
"sebastian/comparator": "^7.1.8",
"sebastian/diff": "^7.0.0",
"sebastian/diff": "^7.0.1",
"sebastian/environment": "^8.1.2",
"sebastian/exporter": "^7.0.3",
"sebastian/global-state": "^8.0.3",
@@ -2024,7 +2024,7 @@
"support": {
"issues": "https://github.com/sebastianbergmann/phpunit/issues",
"security": "https://github.com/sebastianbergmann/phpunit/security/policy",
"source": "https://github.com/sebastianbergmann/phpunit/tree/12.5.33"
"source": "https://github.com/sebastianbergmann/phpunit/tree/12.5.34"
},
"funding": [
{
@@ -2032,7 +2032,7 @@
"type": "other"
}
],
"time": "2026-07-28T13:58:09+00:00"
"time": "2026-08-27T08:38:28+00:00"
},
{
"name": "sebastian/cli-parser",
@@ -2255,24 +2255,24 @@
},
{
"name": "sebastian/diff",
"version": "7.0.0",
"version": "7.0.1",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/diff.git",
"reference": "7ab1ea946c012266ca32390913653d844ecd085f"
"reference": "cd4cabe39f8a4e8ee6818ba99f10a05561ea4ad6"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/7ab1ea946c012266ca32390913653d844ecd085f",
"reference": "7ab1ea946c012266ca32390913653d844ecd085f",
"url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/cd4cabe39f8a4e8ee6818ba99f10a05561ea4ad6",
"reference": "cd4cabe39f8a4e8ee6818ba99f10a05561ea4ad6",
"shasum": ""
},
"require": {
"php": ">=8.3"
},
"require-dev": {
"phpunit/phpunit": "^12.0",
"symfony/process": "^7.2"
"phpunit/phpunit": "^12.5.33",
"symfony/process": "^7.4.17"
},
"type": "library",
"extra": {
@@ -2310,15 +2310,27 @@
"support": {
"issues": "https://github.com/sebastianbergmann/diff/issues",
"security": "https://github.com/sebastianbergmann/diff/security/policy",
"source": "https://github.com/sebastianbergmann/diff/tree/7.0.0"
"source": "https://github.com/sebastianbergmann/diff/tree/7.0.1"
},
"funding": [
{
"url": "https://github.com/sebastianbergmann",
"type": "github"
},
{
"url": "https://liberapay.com/sebastianbergmann",
"type": "liberapay"
},
{
"url": "https://thanks.dev/u/gh/sebastianbergmann",
"type": "thanks_dev"
},
{
"url": "https://tidelift.com/funding/github/packagist/sebastian/diff",
"type": "tidelift"
}
],
"time": "2025-02-07T04:55:46+00:00"
"time": "2026-08-25T15:35:54+00:00"
},
{
"name": "sebastian/environment",
@@ -15,6 +15,9 @@ final readonly class TerminationReport
public array $failures = [],
public bool $deadlineExceeded = false,
public bool $limitExceeded = false,
public int $deferredListenerInvocations = 0,
public bool $deferredEventLimitExceeded = false,
public bool $deferredListenerInvocationLimitExceeded = false,
) {
}
}
@@ -4,7 +4,7 @@ declare(strict_types=1);
namespace KTXC\Console\Event;
use KTXF\Event\EventListenerRegistry;
use KTXC\Event\EventListenerRegistry;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace KTXC\Console\Firewall;
use KTXC\Service\FirewallService;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand(name: 'firewall:maintenance', description: 'Remove expired firewall data and record the outcome')]
final class FirewallMaintenanceCommand extends Command
{
public function __construct(private readonly FirewallService $firewall)
{
parent::__construct();
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
try {
$result = $this->firewall->cleanup();
} catch (\Throwable $error) {
$io->error('Firewall maintenance failed: '.$error->getMessage());
return Command::FAILURE;
}
$io->success(sprintf(
'Firewall maintenance complete: %d expired rules, %d old logs, and %d expired claims removed.',
$result['expiredRules'],
$result['oldLogs'],
$result['expiredBruteForceClaims']
));
return Command::SUCCESS;
}
}
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace KTXC\Console\Firewall;
use KTXC\Stores\FirewallStore;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand(name: 'firewall:setup', description: 'Install or verify firewall database indexes')]
final class FirewallSetupCommand extends Command
{
public function __construct(private readonly FirewallStore $store)
{
parent::__construct();
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
try {
$indexes = $this->store->ensureIndexes();
} catch (\Throwable $error) {
$io->error('Firewall database setup failed: '.$error->getMessage());
return Command::FAILURE;
}
$io->success(sprintf('Firewall database setup complete. %d indexes verified.', count($indexes)));
return Command::SUCCESS;
}
}
@@ -4,10 +4,12 @@ declare(strict_types=1);
namespace KTXC\Console\Tenant;
use KTXC\Context\TenantContext;
use KTXC\Models\Tenant\DomainCollection;
use KTXC\Models\Tenant\TenantConfiguration;
use KTXC\Models\Tenant\TenantObject;
use KTXC\Service\TenantService;
use KTXC\Service\UserAccountsService;
use KTXC\Stores\UserAccountsStore;
use KTXC\Stores\UserRolesStore;
use KTXF\Utile\UUID;
@@ -35,6 +37,8 @@ class TenantCreateCommand extends Command
private readonly TenantService $tenantService,
private readonly UserRolesStore $rolesStore,
private readonly UserAccountsStore $userStore,
private readonly UserAccountsService $userService,
private readonly TenantContext $tenantContext,
private readonly LoggerInterface $logger
) {
parent::__construct();
@@ -97,6 +101,10 @@ class TenantCreateCommand extends Command
$io->error('Failed to create tenant.');
return Command::FAILURE;
}
if (!$this->tenantContext->resolveIdentifier($identifier)) {
throw new \RuntimeException("Failed to initialize tenant context for '{$identifier}'.");
}
$identifier = $this->tenantContext->requireIdentifier();
$this->logger->info('Tenant created via console', [
'identifier' => $identifier,
@@ -134,7 +142,7 @@ class TenantCreateCommand extends Command
if ($this->userStore->fetchByIdentity($identifier, $adminIdentity)) {
$io->warning("User '{$adminIdentity}' already exists in tenant '{$identifier}'; skipping admin user creation.");
} else {
$this->userStore->createUser($identifier, [
$this->userService->createUser([
'identity' => $adminIdentity,
'label' => 'Administrator',
'enabled' => true,
@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace KTXC\Console\Tenant;
use KTXC\SystemStore\SystemStoreConfigurationService;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand(name: 'tenant:store:list', description: 'List logical stores configured for a tenant')]
class TenantStoreListCommand extends Command
{
public function __construct(private readonly SystemStoreConfigurationService $stores)
{
parent::__construct();
}
protected function configure(): void
{
$this->addArgument('tenant', InputArgument::REQUIRED, 'Tenant identifier');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$tenant = (string) $input->getArgument('tenant');
try {
$stores = $this->stores->list($tenant);
if ($stores === []) {
$io->text("No logical stores configured for tenant '{$tenant}'.");
return Command::SUCCESS;
}
$rows = [];
foreach ($stores as $name => $store) {
$rows[] = [$name, $store->provider, (string) $store->service, $store->namespace];
}
$io->table(['Name', 'Provider', 'Service', 'Namespace'], $rows);
return Command::SUCCESS;
} catch (\Throwable $error) {
$io->error('Failed to list tenant stores: ' . $error->getMessage());
return Command::FAILURE;
}
}
}
@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace KTXC\Console\Tenant;
use KTXC\SystemStore\SystemStoreConfigurationService;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand(name: 'tenant:store:remove', description: 'Remove a logical store from a tenant')]
class TenantStoreRemoveCommand extends Command
{
public function __construct(
private readonly SystemStoreConfigurationService $stores,
private readonly LoggerInterface $logger,
) {
parent::__construct();
}
protected function configure(): void
{
$this
->addArgument('tenant', InputArgument::REQUIRED, 'Tenant identifier')
->addArgument('name', InputArgument::REQUIRED, 'Logical store name');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$tenant = (string) $input->getArgument('tenant');
$name = (string) $input->getArgument('name');
try {
if (!$this->stores->remove($tenant, $name)) {
$io->warning("Logical store '{$name}' was not configured for tenant '{$tenant}'.");
return Command::SUCCESS;
}
$this->logger->info('Tenant logical store removed via console', compact('tenant', 'name'));
$io->success("Logical store '{$name}' removed from tenant '{$tenant}'.");
return Command::SUCCESS;
} catch (\Throwable $error) {
$this->logger->error('Tenant logical store removal failed', [
'tenant' => $tenant,
'name' => $name,
'error' => $error->getMessage(),
]);
$io->error('Failed to remove tenant store: ' . $error->getMessage());
return Command::FAILURE;
}
}
}
@@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
namespace KTXC\Console\Tenant;
use KTXC\SystemStore\SystemStoreConfigurationService;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand(name: 'tenant:store:set', description: 'Configure a logical store for a tenant')]
class TenantStoreSetCommand extends Command
{
public function __construct(
private readonly SystemStoreConfigurationService $stores,
private readonly LoggerInterface $logger,
) {
parent::__construct();
}
protected function configure(): void
{
$this
->addArgument('tenant', InputArgument::REQUIRED, 'Tenant identifier')
->addArgument('name', InputArgument::REQUIRED, 'Logical store name, such as previews')
->addArgument('provider', InputArgument::REQUIRED, 'System-store provider identifier')
->addArgument('service', InputArgument::REQUIRED, 'System-store service identifier')
->addArgument('namespace', InputArgument::REQUIRED, 'Provider key namespace');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$tenant = (string) $input->getArgument('tenant');
$name = (string) $input->getArgument('name');
$provider = (string) $input->getArgument('provider');
$service = (string) $input->getArgument('service');
$namespace = (string) $input->getArgument('namespace');
try {
$this->stores->set($tenant, $name, $provider, $service, $namespace);
$this->logger->info('Tenant logical store configured via console', compact(
'tenant', 'name', 'provider', 'service', 'namespace',
));
$io->success("Logical store '{$name}' configured for tenant '{$tenant}'.");
return Command::SUCCESS;
} catch (\Throwable $error) {
$this->logger->error('Tenant logical store configuration failed', [
'tenant' => $tenant,
'name' => $name,
'error' => $error->getMessage(),
]);
$io->error('Failed to configure tenant store: ' . $error->getMessage());
return Command::FAILURE;
}
}
}
+7 -5
View File
@@ -4,7 +4,8 @@ declare(strict_types=1);
namespace KTXC\Console\User;
use KTXC\Service\TenantService;
use KTXC\Context\TenantContext;
use KTXC\Service\UserAccountsService;
use KTXC\Stores\UserAccountsStore;
use KTXC\Stores\UserRolesStore;
use Psr\Log\LoggerInterface;
@@ -28,8 +29,9 @@ use Symfony\Component\Console\Style\SymfonyStyle;
class UserCreateCommand extends Command
{
public function __construct(
private readonly TenantService $tenantService,
private readonly TenantContext $tenantContext,
private readonly UserAccountsStore $userStore,
private readonly UserAccountsService $userService,
private readonly UserRolesStore $rolesStore,
private readonly LoggerInterface $logger
) {
@@ -59,11 +61,11 @@ class UserCreateCommand extends Command
$io->title('Create User');
try {
// Ensure the tenant exists
if (!$this->tenantService->fetchById($tenant)) {
if (!$this->tenantContext->resolveIdentifier($tenant)) {
$io->error("Tenant '{$tenant}' not found.");
return Command::FAILURE;
}
$tenant = $this->tenantContext->requireIdentifier();
// Ensure identity is unique within the tenant
if ($this->userStore->fetchByIdentity($tenant, $identity)) {
@@ -95,7 +97,7 @@ class UserCreateCommand extends Command
$userData['uid'] = $input->getOption('uid');
}
$user = $this->userStore->createUser($tenant, $userData);
$user = $this->userService->createUser($userData);
$this->logger->info('User created via console', [
'tenant' => $tenant,
+11 -1
View File
@@ -4,6 +4,8 @@ declare(strict_types=1);
namespace KTXC\Console\User;
use KTXC\Context\TenantContext;
use KTXC\Service\UserAccountsService;
use KTXC\Stores\UserAccountsStore;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
@@ -26,7 +28,9 @@ use Symfony\Component\Console\Style\SymfonyStyle;
class UserDeleteCommand extends Command
{
public function __construct(
private readonly TenantContext $tenantContext,
private readonly UserAccountsStore $userStore,
private readonly UserAccountsService $userService,
private readonly LoggerInterface $logger
) {
parent::__construct();
@@ -52,6 +56,12 @@ class UserDeleteCommand extends Command
$io->title('Delete User');
try {
if (!$this->tenantContext->resolveIdentifier($tenant)) {
$io->error("Tenant '{$tenant}' not found.");
return Command::FAILURE;
}
$tenant = $this->tenantContext->requireIdentifier();
$user = $this->userStore->fetchByIdentity($tenant, $identity);
if (!$user) {
@@ -64,7 +74,7 @@ class UserDeleteCommand extends Command
return Command::SUCCESS;
}
if (!$this->userStore->deleteUser($tenant, $user['uid'])) {
if (!$this->userService->deleteUser($user['uid'])) {
$io->error("Failed to delete user '{$identity}'.");
return Command::FAILURE;
}
@@ -92,9 +92,9 @@ class AuthenticationController extends ControllerAbstract
}
$request = AuthenticationRequest::verify($session, $method, $response);
$authResponse = $this->authManager->handle($request);
$response = $this->authManager->handle($request);
return $this->buildJsonResponse($authResponse);
return $this->buildJsonResponse($response);
}
/**
@@ -120,8 +120,8 @@ class AuthenticationController extends ControllerAbstract
$host = $request->getHost();
$callbackUrl = "{$scheme}://{$host}/auth/callback/{$method}";
$authRequest = AuthenticationRequest::redirect($sessionId, $method, $callbackUrl, $returnUrl);
$response = $this->authManager->handle($authRequest);
$request = AuthenticationRequest::redirect($sessionId, $method, $callbackUrl, $returnUrl);
$response = $this->authManager->handle($request);
return $this->buildJsonResponse($response);
}
@@ -142,8 +142,8 @@ class AuthenticationController extends ControllerAbstract
return $this->redirectWithError('Missing state parameter');
}
$authRequest = AuthenticationRequest::callback($sessionId, $provider, $params);
$response = $this->authManager->handle($authRequest);
$request = AuthenticationRequest::callback($sessionId, $provider, $params);
$response = $this->authManager->handle($request);
if ($response->isSuccess()) {
$returnUrl = $response->returnUrl ?? '/';
@@ -178,8 +178,8 @@ class AuthenticationController extends ControllerAbstract
);
}
$authRequest = AuthenticationRequest::status($sessionId);
$response = $this->authManager->handle($authRequest);
$request = AuthenticationRequest::status($sessionId);
$response = $this->authManager->handle($request);
return $this->buildJsonResponse($response);
}
@@ -192,8 +192,8 @@ class AuthenticationController extends ControllerAbstract
{
$sessionId = $request->query->get('session', '');
$authRequest = AuthenticationRequest::cancel($sessionId);
$this->authManager->handle($authRequest);
$request = AuthenticationRequest::cancel($sessionId);
$this->authManager->handle($request);
return new JsonResponse(['status' => 'cancelled', 'message' => 'Session cancelled']);
}
@@ -217,8 +217,8 @@ class AuthenticationController extends ControllerAbstract
);
}
$authRequest = AuthenticationRequest::refresh($refreshToken);
$response = $this->authManager->handle($authRequest);
$request = AuthenticationRequest::refresh($refreshToken);
$response = $this->authManager->handle($request);
if ($response->isFailed()) {
$httpResponse = new JsonResponse($response->toArray(), $response->httpStatus);
@@ -259,8 +259,8 @@ class AuthenticationController extends ControllerAbstract
{
$token = $request->cookies->get('accessToken');
$authRequest = AuthenticationRequest::logout($token, false);
$this->authManager->handle($authRequest);
$request = AuthenticationRequest::logout($token, false);
$this->authManager->handle($request);
$response = new JsonResponse(['status' => 'success', 'message' => 'Logged out successfully']);
return $this->clearTokenCookies($response);
@@ -274,8 +274,8 @@ class AuthenticationController extends ControllerAbstract
{
$token = $request->cookies->get('accessToken');
$authRequest = AuthenticationRequest::logout($token, true);
$this->authManager->handle($authRequest);
$request = AuthenticationRequest::logout($token, true);
$this->authManager->handle($request);
$response = new JsonResponse(['status' => 'success', 'message' => 'Logged out from all devices']);
return $this->clearTokenCookies($response);
+465
View File
@@ -0,0 +1,465 @@
<?php
declare(strict_types=1);
namespace KTXC\Controllers;
use KTXC\Http\Request\Request;
use KTXC\Http\Response\JsonResponse;
use KTXC\Service\FirewallRuleConflictException;
use KTXC\Service\SystemFirewallLogService;
use KTXC\Service\SystemFirewallRuleService;
use KTXC\Service\SystemFirewallStatusService;
use KTXC\Service\TenantFirewallLogService;
use KTXC\Service\TenantFirewallRuleService;
use KTXC\Service\TenantFirewallStatusService;
use KTXF\Controller\ControllerAbstract;
use KTXF\Routing\Attributes\AuthenticatedRoute;
final class FirewallController extends ControllerAbstract
{
public function __construct(
private readonly TenantFirewallRuleService $tenantRules,
private readonly SystemFirewallRuleService $systemRules,
private readonly TenantFirewallLogService $tenantLogs,
private readonly SystemFirewallLogService $systemLogs,
private readonly TenantFirewallStatusService $tenantStatus,
private readonly SystemFirewallStatusService $systemStatus,
) {
}
#[AuthenticatedRoute(
'/firewall/rules',
name: 'firewall.tenant.rules.list',
permissions: [TenantFirewallRuleService::PERMISSION_READ],
)]
public function tenantRules(
string $status = 'active',
?string $type = null,
?string $action = null,
string $limit = '50',
string $offset = '0'
): JsonResponse {
return $this->queryResponse(
fn(int $parsedLimit, int $parsedOffset): array => $this->tenantRules->queryRules(
$status,
$type,
$action,
$parsedLimit,
$parsedOffset
),
$limit,
$offset
);
}
#[AuthenticatedRoute(
'/firewall/rules/{ruleId}',
name: 'firewall.tenant.rules.fetch',
permissions: [TenantFirewallRuleService::PERMISSION_READ],
)]
public function tenantRule(string $ruleId): JsonResponse
{
return $this->ruleResponse($this->tenantRules->fetchRule($ruleId));
}
#[AuthenticatedRoute(
'/firewall/effective-policy',
name: 'firewall.tenant.policy.effective',
permissions: [TenantFirewallRuleService::PERMISSION_READ],
)]
public function effectivePolicy(): JsonResponse
{
return new JsonResponse($this->tenantRules->effectivePolicy());
}
#[AuthenticatedRoute(
'/firewall/system/rules',
name: 'firewall.system.rules.list',
permissions: [SystemFirewallRuleService::PERMISSION_READ],
)]
public function systemRules(
string $status = 'active',
?string $type = null,
?string $action = null,
string $limit = '50',
string $offset = '0'
): JsonResponse {
return $this->queryResponse(
fn(int $parsedLimit, int $parsedOffset): array => $this->systemRules->queryRules(
$status,
$type,
$action,
$parsedLimit,
$parsedOffset
),
$limit,
$offset
);
}
#[AuthenticatedRoute(
'/firewall/system/rules/{ruleId}',
name: 'firewall.system.rules.fetch',
permissions: [SystemFirewallRuleService::PERMISSION_READ],
)]
public function systemRule(string $ruleId): JsonResponse
{
return $this->ruleResponse($this->systemRules->fetchRule($ruleId));
}
#[AuthenticatedRoute(
'/firewall/rules',
name: 'firewall.tenant.rules.create',
methods: ['POST'],
permissions: [TenantFirewallRuleService::PERMISSION_MANAGE],
)]
public function createTenantRule(
Request $request,
string $type,
string $action,
string $value,
string $reason,
?int $durationSeconds = null,
bool $confirmCurrentIp = false
): JsonResponse {
return $this->mutationResponse(fn() => $this->tenantRules->createRule(
$type,
$action,
$value,
$reason,
$durationSeconds,
$request->getClientIp(),
$confirmCurrentIp
));
}
#[AuthenticatedRoute(
'/firewall/system/rules',
name: 'firewall.system.rules.create',
methods: ['POST'],
permissions: [SystemFirewallRuleService::PERMISSION_MANAGE],
)]
public function createSystemRule(
Request $request,
string $type,
string $action,
string $value,
string $reason,
?int $durationSeconds = null,
bool $confirmCurrentIp = false
): JsonResponse {
return $this->mutationResponse(fn() => $this->systemRules->createRule(
$type,
$action,
$value,
$reason,
$durationSeconds,
$request->getClientIp(),
$confirmCurrentIp
));
}
#[AuthenticatedRoute(
'/firewall/rules/{ruleId}',
name: 'firewall.tenant.rules.update',
methods: ['PATCH'],
permissions: [TenantFirewallRuleService::PERMISSION_MANAGE],
)]
public function updateTenantRule(
Request $request,
string $ruleId,
string $operation,
string $reason,
?int $durationSeconds = null,
bool $confirmCurrentIp = false
): JsonResponse {
return $this->lifecycleResponse(fn() => match ($operation) {
'disable' => $this->tenantRules->disableRule($ruleId, $reason),
'enable' => $this->tenantRules->enableRule(
$ruleId, $reason, $request->getClientIp(), $confirmCurrentIp
),
'extend' => $this->tenantRules->extendRule(
$ruleId,
$durationSeconds ?? throw new \InvalidArgumentException('Rule extension duration is required.'),
$reason
),
default => throw new \InvalidArgumentException('Invalid firewall rule operation.'),
});
}
#[AuthenticatedRoute(
'/firewall/system/rules/{ruleId}',
name: 'firewall.system.rules.update',
methods: ['PATCH'],
permissions: [SystemFirewallRuleService::PERMISSION_MANAGE],
)]
public function updateSystemRule(
Request $request,
string $ruleId,
string $operation,
string $reason,
?int $durationSeconds = null,
bool $confirmCurrentIp = false
): JsonResponse {
return $this->lifecycleResponse(fn() => match ($operation) {
'disable' => $this->systemRules->disableRule($ruleId, $reason),
'enable' => $this->systemRules->enableRule(
$ruleId, $reason, $request->getClientIp(), $confirmCurrentIp
),
'extend' => $this->systemRules->extendRule(
$ruleId,
$durationSeconds ?? throw new \InvalidArgumentException('Rule extension duration is required.'),
$reason
),
default => throw new \InvalidArgumentException('Invalid firewall rule operation.'),
});
}
#[AuthenticatedRoute(
'/firewall/rules/{ruleId}',
name: 'firewall.tenant.rules.delete',
methods: ['DELETE'],
permissions: [TenantFirewallRuleService::PERMISSION_MANAGE],
)]
public function deleteTenantRule(string $ruleId, string $reason): JsonResponse
{
return $this->lifecycleResponse(fn() => $this->tenantRules->removeRule($ruleId, $reason));
}
#[AuthenticatedRoute(
'/firewall/system/rules/{ruleId}',
name: 'firewall.system.rules.delete',
methods: ['DELETE'],
permissions: [SystemFirewallRuleService::PERMISSION_MANAGE],
)]
public function deleteSystemRule(string $ruleId, string $reason): JsonResponse
{
return $this->lifecycleResponse(fn() => $this->systemRules->removeRule($ruleId, $reason));
}
#[AuthenticatedRoute(
'/firewall/logs',
name: 'firewall.tenant.logs.list',
permissions: [TenantFirewallLogService::PERMISSION_READ],
)]
public function tenantLogs(
?string $ipAddress = null,
?string $eventType = null,
?string $result = null,
?string $ruleId = null,
?string $ruleScope = null,
?string $from = null,
?string $to = null,
string $limit = '50',
string $offset = '0'
): JsonResponse {
return $this->queryResponse(
fn(int $parsedLimit, int $parsedOffset): array => $this->tenantLogs->query(
compact('ipAddress', 'eventType', 'result', 'ruleId', 'ruleScope', 'from', 'to'),
$parsedLimit,
$parsedOffset
),
$limit,
$offset
);
}
#[AuthenticatedRoute(
'/firewall/system/logs',
name: 'firewall.system.logs.list',
permissions: [SystemFirewallLogService::PERMISSION_READ],
)]
public function systemLogs(
?string $tenantId = null,
?string $ipAddress = null,
?string $eventType = null,
?string $result = null,
?string $ruleId = null,
?string $ruleScope = null,
?string $from = null,
?string $to = null,
string $limit = '50',
string $offset = '0'
): JsonResponse {
return $this->queryResponse(
fn(int $parsedLimit, int $parsedOffset): array => $this->systemLogs->query(
$tenantId,
compact('ipAddress', 'eventType', 'result', 'ruleId', 'ruleScope', 'from', 'to'),
$parsedLimit,
$parsedOffset
),
$limit,
$offset
);
}
#[AuthenticatedRoute(
'/firewall/metrics',
name: 'firewall.tenant.metrics.read',
permissions: [TenantFirewallLogService::PERMISSION_READ],
)]
public function tenantMetrics(?string $since = null): JsonResponse
{
return $this->readResponse(fn(): array => $this->tenantStatus->metrics($since));
}
#[AuthenticatedRoute(
'/firewall/configuration',
name: 'firewall.tenant.configuration.read',
permissions: [TenantFirewallStatusService::PERMISSION_SETTINGS_READ],
)]
public function tenantConfiguration(): JsonResponse
{
return new JsonResponse($this->tenantStatus->configuration());
}
#[AuthenticatedRoute(
'/firewall/configuration',
name: 'firewall.tenant.configuration.update',
methods: ['PUT'],
permissions: [TenantFirewallStatusService::PERMISSION_SETTINGS_MANAGE],
)]
public function updateTenantConfiguration(
bool $enabled,
int $maxAuthFailures,
int $authFailureWindow,
int $autoBlockDuration,
string $reason
): JsonResponse {
return $this->settingsResponse(fn() => $this->tenantStatus->updateConfiguration(
$enabled, $maxAuthFailures, $authFailureWindow, $autoBlockDuration, $reason
));
}
#[AuthenticatedRoute(
'/firewall/system/tenants/{tenantId}/configuration',
name: 'firewall.system.tenant.configuration.update',
methods: ['PUT'],
permissions: [SystemFirewallStatusService::PERMISSION_SETTINGS_MANAGE],
)]
public function updateSystemTenantConfiguration(
string $tenantId,
bool $enabled,
int $maxAuthFailures,
int $authFailureWindow,
int $autoBlockDuration,
string $reason
): JsonResponse {
return $this->settingsResponse(fn() => $this->systemStatus->updateTenantConfiguration(
$tenantId, $enabled, $maxAuthFailures, $authFailureWindow, $autoBlockDuration, $reason
));
}
#[AuthenticatedRoute(
'/firewall/system/metrics',
name: 'firewall.system.metrics.read',
permissions: [SystemFirewallLogService::PERMISSION_READ],
)]
public function systemMetrics(?string $tenantId = null, ?string $since = null): JsonResponse
{
return $this->readResponse(fn(): array => $this->systemStatus->metrics($tenantId, $since));
}
#[AuthenticatedRoute(
'/firewall/system/maintenance',
name: 'firewall.system.maintenance.read',
permissions: [SystemFirewallStatusService::PERMISSION_MAINTENANCE_READ],
)]
public function maintenanceStatus(): JsonResponse
{
return new JsonResponse($this->systemStatus->maintenanceStatus());
}
private function queryResponse(callable $query, string $limit, string $offset): JsonResponse
{
try {
if (!ctype_digit($limit) || !ctype_digit($offset)) {
throw new \InvalidArgumentException('Pagination values must be non-negative integers.');
}
return new JsonResponse($query((int)$limit, (int)$offset));
} catch (\InvalidArgumentException $error) {
return new JsonResponse(['error' => $error->getMessage()], JsonResponse::HTTP_BAD_REQUEST);
}
}
private function ruleResponse(?\JsonSerializable $rule): JsonResponse
{
if ($rule === null) {
return new JsonResponse(['error' => 'Firewall rule not found.'], JsonResponse::HTTP_NOT_FOUND);
}
return new JsonResponse($rule);
}
private function readResponse(callable $read): JsonResponse
{
try {
return new JsonResponse($read());
} catch (\InvalidArgumentException $error) {
return new JsonResponse(['error' => $error->getMessage()], JsonResponse::HTTP_BAD_REQUEST);
}
}
private function mutationResponse(callable $mutation): JsonResponse
{
try {
return new JsonResponse(['rule' => $mutation()], JsonResponse::HTTP_CREATED);
} catch (FirewallRuleConflictException $error) {
return new JsonResponse(['error' => [
'code' => $error->conflictCode,
'message' => $error->getMessage(),
]], JsonResponse::HTTP_CONFLICT);
} catch (\InvalidArgumentException $error) {
return new JsonResponse(['error' => [
'code' => 'invalid_firewall_rule',
'message' => $error->getMessage(),
]], JsonResponse::HTTP_BAD_REQUEST);
}
}
private function lifecycleResponse(callable $mutation): JsonResponse
{
try {
$rule = $mutation();
if ($rule === null) {
return new JsonResponse(['error' => [
'code' => 'firewall_rule_not_found',
'message' => 'Firewall rule not found.',
]], JsonResponse::HTTP_NOT_FOUND);
}
return new JsonResponse(['rule' => $rule]);
} catch (FirewallRuleConflictException $error) {
return new JsonResponse(['error' => [
'code' => $error->conflictCode,
'message' => $error->getMessage(),
]], JsonResponse::HTTP_CONFLICT);
} catch (\InvalidArgumentException $error) {
return new JsonResponse(['error' => [
'code' => 'invalid_firewall_rule',
'message' => $error->getMessage(),
]], JsonResponse::HTTP_BAD_REQUEST);
}
}
private function settingsResponse(callable $mutation): JsonResponse
{
try {
$configuration = $mutation();
if ($configuration === null) {
return new JsonResponse(['error' => [
'code' => 'tenant_not_found',
'message' => 'Tenant not found.',
]], JsonResponse::HTTP_NOT_FOUND);
}
return new JsonResponse(['configuration' => $configuration]);
} catch (\InvalidArgumentException $error) {
return new JsonResponse(['error' => [
'code' => 'invalid_firewall_configuration',
'message' => $error->getMessage(),
]], JsonResponse::HTTP_BAD_REQUEST);
}
}
}
+1 -1
View File
@@ -66,6 +66,6 @@ class ObjectId
*/
public static function isValid(string $id): bool
{
return MongoObjectId::isValid($id);
return preg_match('/^[a-f0-9]{24}$/iD', $id) === 1;
}
}
@@ -2,7 +2,7 @@
declare(strict_types=1);
namespace KTXF\Event;
namespace KTXC\Event;
interface DeferredEventProcessorInterface
{
@@ -2,7 +2,7 @@
declare(strict_types=1);
namespace KTXF\Event;
namespace KTXC\Event;
final readonly class DeferredProcessingResult
{
@@ -11,6 +11,9 @@ final readonly class DeferredProcessingResult
public int $remaining,
public bool $deadlineExceeded,
public bool $limitExceeded = false,
public int $listenerInvocations = 0,
public bool $eventLimitExceeded = false,
public bool $listenerInvocationLimitExceeded = false,
) {
}
}
+161
View File
@@ -0,0 +1,161 @@
<?php
declare(strict_types=1);
namespace KTXC\Event;
use KTXF\Event\DeliveryMode;
use KTXF\Event\Event;
use KTXF\Event\EventDispatcherInterface;
use KTXF\Event\FailurePolicy;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;
final class EventDispatcher implements EventDispatcherInterface, DeferredEventProcessorInterface
{
private const DEFAULT_DEFERRED_PROCESSING_TIMEOUT_SECONDS = 300.0;
private const DEFAULT_MAX_DEFERRED_EVENTS = 1000;
private const DEFAULT_MAX_DEFERRED_LISTENER_INVOCATIONS = 50000;
/** @var array<string, list<Event>> */
private array $deferred = [];
private ?string $activeExecution = null;
private int $dispatchDepth = 0;
public function __construct(
private readonly EventListenerRegistry $registry,
private readonly ContainerInterface $container,
private readonly LoggerInterface $logger,
private readonly float $deferredProcessingTimeoutSeconds = self::DEFAULT_DEFERRED_PROCESSING_TIMEOUT_SECONDS,
private readonly int $maxDeferredEvents = self::DEFAULT_MAX_DEFERRED_EVENTS,
private readonly int $maxDeferredListenerInvocations = self::DEFAULT_MAX_DEFERRED_LISTENER_INVOCATIONS,
) {
if ($this->deferredProcessingTimeoutSeconds <= 0) {
throw new \InvalidArgumentException('The deferred processing timeout must be greater than zero.');
}
if ($this->maxDeferredEvents <= 0) {
throw new \InvalidArgumentException('The deferred event limit must be greater than zero.');
}
if ($this->maxDeferredListenerInvocations <= 0) {
throw new \InvalidArgumentException('The deferred listener invocation limit must be greater than zero.');
}
}
public function dispatch(Event $event): void
{
if (++$this->dispatchDepth > 32) {
--$this->dispatchDepth;
throw new \RuntimeException('Event dispatch recursion limit exceeded.');
}
try {
$this->invoke($event, DeliveryMode::Immediate);
if ($this->registry->listeners($event->label(), DeliveryMode::Deferred) !== []) {
if ($this->activeExecution === null) {
throw new \LogicException('Deferred events require an active execution scope.');
}
$this->deferred[$this->activeExecution][] = $event;
}
} finally {
--$this->dispatchDepth;
}
}
public function beginExecution(string $executionId): void
{
if ($this->activeExecution !== null) {
throw new \LogicException('An event execution scope is already active.');
}
$this->activeExecution = $executionId;
$this->deferred[$executionId] = [];
}
public function processDeferred(string $executionId): DeferredProcessingResult
{
if ($this->activeExecution !== $executionId) {
throw new \LogicException('Cannot process deferred events for an inactive execution.');
}
try {
$processedEvents = 0;
$listenerInvocations = 0;
$deadline = microtime(true) + $this->deferredProcessingTimeoutSeconds;
$deadlineExceeded = false;
$eventLimitExceeded = false;
$listenerInvocationLimitExceeded = false;
while (($event = array_shift($this->deferred[$executionId])) !== null) {
if ($processedEvents >= $this->maxDeferredEvents) {
$eventLimitExceeded = true;
array_unshift($this->deferred[$executionId], $event);
break;
}
if (microtime(true) >= $deadline) {
$deadlineExceeded = true;
array_unshift($this->deferred[$executionId], $event);
break;
}
$eventListenerCount = count($this->registry->listeners(
$event->label(),
DeliveryMode::Deferred,
));
if ($listenerInvocations + $eventListenerCount > $this->maxDeferredListenerInvocations) {
$listenerInvocationLimitExceeded = true;
array_unshift($this->deferred[$executionId], $event);
break;
}
$listenerInvocations += $this->invoke($event, DeliveryMode::Deferred);
$processedEvents++;
}
return new DeferredProcessingResult(
processed: $processedEvents,
remaining: count($this->deferred[$executionId]),
deadlineExceeded: $deadlineExceeded,
limitExceeded: $eventLimitExceeded || $listenerInvocationLimitExceeded,
listenerInvocations: $listenerInvocations,
eventLimitExceeded: $eventLimitExceeded,
listenerInvocationLimitExceeded: $listenerInvocationLimitExceeded,
);
} finally {
$this->discardDeferred($executionId);
}
}
public function discardDeferred(string $executionId): void
{
unset($this->deferred[$executionId]);
if ($this->activeExecution === $executionId) {
$this->activeExecution = null;
}
}
private function invoke(Event $event, DeliveryMode $delivery): int
{
$processed = 0;
foreach ($this->registry->listeners($event->label(), $delivery) as $listener) {
if ($event->isPropagationStopped()) {
break;
}
$processed++;
try {
$service = $this->container->get($listener->service);
$service->{$listener->method}($event);
} catch (\Throwable $error) {
$this->logger->error('Event listener failed.', [
'event' => $event->label(),
'module' => $listener->module,
'listener' => $listener->service . '::' . $listener->method,
'exception' => $error,
]);
if ($listener->failurePolicy === FailurePolicy::Propagate) {
throw $error;
}
}
}
return $processed;
}
}
@@ -2,7 +2,10 @@
declare(strict_types=1);
namespace KTXF\Event;
namespace KTXC\Event;
use KTXF\Event\DeliveryMode;
use KTXF\Event\FailurePolicy;
final readonly class EventListenerDefinition
{
@@ -2,11 +2,14 @@
declare(strict_types=1);
namespace KTXF\Event;
namespace KTXC\Event;
use KTXF\Event\DeliveryMode;
use KTXF\Event\EventListenerRegistrarInterface;
use KTXF\Event\FailurePolicy;
use Psr\Container\ContainerInterface;
final class EventListenerRegistry
final class EventListenerRegistry implements EventListenerRegistrarInterface
{
/** @var array<string, list<EventListenerDefinition>> */
private array $listeners = [];
+32
View File
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace KTXC\Http\Request;
/**
* Holds the HTTP request for the duration of the current runtime execution.
*/
final class RequestContext
{
private ?Request $request = null;
public function initialize(Request $request): void
{
if ($this->request !== null) {
throw new \LogicException('The request context has already been initialized.');
}
$this->request = $request;
}
public function current(): ?Request
{
return $this->request;
}
public function clear(): void
{
$this->request = null;
}
}
+14 -3
View File
@@ -27,10 +27,11 @@ use KTXC\Module\ModuleManager;
use Psr\Log\LoggerInterface;
use KTXC\Logger\LoggerFactory;
use KTXC\Logger\TenantAwareLogger;
use KTXF\Event\DeferredEventProcessorInterface;
use KTXF\Event\EventDispatcher;
use KTXC\Event\DeferredEventProcessorInterface;
use KTXC\Event\EventDispatcher;
use KTXC\Event\EventListenerRegistry;
use KTXF\Event\EventDispatcherInterface;
use KTXF\Event\EventListenerRegistry;
use KTXF\Event\EventListenerRegistrarInterface;
use KTXF\Cache\EphemeralCacheInterface;
use KTXF\Cache\PersistentCacheInterface;
use KTXF\Cache\BlobCacheInterface;
@@ -237,6 +238,9 @@ class Kernel implements KernelInterface
$remaining = 0;
$deadlineExceeded = false;
$limitExceeded = false;
$listenerInvocations = 0;
$eventLimitExceeded = false;
$listenerInvocationLimitExceeded = false;
$failures = [];
try {
@@ -248,6 +252,9 @@ class Kernel implements KernelInterface
$remaining = $result->remaining;
$deadlineExceeded = $result->deadlineExceeded;
$limitExceeded = $result->limitExceeded;
$listenerInvocations = $result->listenerInvocations;
$eventLimitExceeded = $result->eventLimitExceeded;
$listenerInvocationLimitExceeded = $result->listenerInvocationLimitExceeded;
}
} catch (\Throwable $e) {
$failures[] = $e;
@@ -286,6 +293,9 @@ class Kernel implements KernelInterface
failures: $failures,
deadlineExceeded: $deadlineExceeded,
limitExceeded: $limitExceeded,
deferredListenerInvocations: $listenerInvocations,
deferredEventLimitExceeded: $eventLimitExceeded,
deferredListenerInvocationLimitExceeded: $listenerInvocationLimitExceeded,
);
}
@@ -410,6 +420,7 @@ class Kernel implements KernelInterface
EventDispatcherInterface::class => \DI\get(EventDispatcher::class),
DeferredEventProcessorInterface::class => \DI\get(EventDispatcher::class),
EventListenerRegistrarInterface::class => \DI\get(EventListenerRegistry::class),
// Ephemeral Cache - for short-lived data (sessions, rate limits, challenges)
EphemeralCacheInterface::class => function(ContainerInterface $c) use ($projectDir) {
$storeType = $c->has('cache.ephemeral') ? $c->get('cache.ephemeral') : 'file';
+65 -3
View File
@@ -13,6 +13,7 @@ class FirewallLogObject implements \JsonSerializable, JsonDeserializable
{
public const RESULT_ALLOWED = 'allowed';
public const RESULT_BLOCKED = 'blocked';
public const RESULT_RECORDED = 'recorded';
public const EVENT_AUTH_FAILURE = 'auth_failure';
public const EVENT_RATE_LIMIT = 'rate_limit';
@@ -20,8 +21,15 @@ class FirewallLogObject implements \JsonSerializable, JsonDeserializable
public const EVENT_SUSPICIOUS = 'suspicious';
public const EVENT_RULE_MATCH = 'rule_match';
public const EVENT_ACCESS_CHECK = 'access_check';
public const EVENT_RULE_CREATED = 'rule_created';
public const EVENT_RULE_EXTENDED = 'rule_extended';
public const EVENT_RULE_ENABLED = 'rule_enabled';
public const EVENT_RULE_DISABLED = 'rule_disabled';
public const EVENT_RULE_REMOVED = 'rule_removed';
public const EVENT_SETTINGS_UPDATED = 'settings_updated';
private ?string $id = null;
private ?string $eventId = null;
private ?string $tenantId = null;
private ?string $ipAddress = null;
private ?string $deviceFingerprint = null;
@@ -31,6 +39,7 @@ class FirewallLogObject implements \JsonSerializable, JsonDeserializable
private ?string $eventType = null;
private ?string $result = null; // allowed, blocked
private ?string $ruleId = null; // Which rule triggered (if any)
private ?string $ruleScope = null; // tenant or system
private ?string $identityId = null; // User ID if authenticated
private ?\DateTimeImmutable $timestamp = null;
private ?array $metadata = null; // Additional context
@@ -50,6 +59,9 @@ class FirewallLogObject implements \JsonSerializable, JsonDeserializable
if (array_key_exists('tenantId', $data)) {
$this->tenantId = $data['tenantId'] !== null ? (string)$data['tenantId'] : null;
}
if (array_key_exists('eventId', $data)) {
$this->eventId = $data['eventId'] !== null ? (string)$data['eventId'] : null;
}
if (array_key_exists('ipAddress', $data)) {
$this->ipAddress = $data['ipAddress'] !== null ? (string)$data['ipAddress'] : null;
}
@@ -74,13 +86,14 @@ class FirewallLogObject implements \JsonSerializable, JsonDeserializable
if (array_key_exists('ruleId', $data)) {
$this->ruleId = $data['ruleId'] !== null ? (string)$data['ruleId'] : null;
}
if (array_key_exists('ruleScope', $data)) {
$this->ruleScope = $data['ruleScope'] !== null ? (string)$data['ruleScope'] : null;
}
if (array_key_exists('identityId', $data)) {
$this->identityId = $data['identityId'] !== null ? (string)$data['identityId'] : null;
}
if (array_key_exists('timestamp', $data)) {
$this->timestamp = $data['timestamp'] !== null
? new \DateTimeImmutable($data['timestamp'])
: null;
$this->timestamp = self::deserializeDate($data['timestamp']);
}
if (array_key_exists('metadata', $data)) {
$this->metadata = $data['metadata'] !== null ? (array)$data['metadata'] : null;
@@ -93,6 +106,7 @@ class FirewallLogObject implements \JsonSerializable, JsonDeserializable
{
return [
'id' => $this->id,
'eventId' => $this->eventId,
'tenantId' => $this->tenantId,
'ipAddress' => $this->ipAddress,
'deviceFingerprint' => $this->deviceFingerprint,
@@ -102,12 +116,31 @@ class FirewallLogObject implements \JsonSerializable, JsonDeserializable
'eventType' => $this->eventType,
'result' => $this->result,
'ruleId' => $this->ruleId,
'ruleScope' => $this->ruleScope,
'identityId' => $this->identityId,
'timestamp' => $this->timestamp?->format(\DateTimeInterface::ATOM),
'metadata' => $this->metadata,
];
}
private static function deserializeDate(mixed $value): ?\DateTimeImmutable
{
if ($value === null) {
return null;
}
if ($value instanceof \MongoDB\BSON\UTCDateTime) {
return \DateTimeImmutable::createFromMutable($value->toDateTime());
}
if ($value instanceof \DateTimeImmutable) {
return $value;
}
if ($value instanceof \DateTimeInterface) {
return \DateTimeImmutable::createFromInterface($value);
}
return new \DateTimeImmutable((string)$value);
}
// Getters and setters
public function getId(): ?string
@@ -121,6 +154,17 @@ class FirewallLogObject implements \JsonSerializable, JsonDeserializable
return $this;
}
public function getEventId(): ?string
{
return $this->eventId;
}
public function setEventId(?string $eventId): self
{
$this->eventId = $eventId;
return $this;
}
public function getTenantId(): ?string
{
return $this->tenantId;
@@ -220,6 +264,24 @@ class FirewallLogObject implements \JsonSerializable, JsonDeserializable
return $this;
}
public function getRuleScope(): ?string
{
return $this->ruleScope;
}
public function setRuleScope(?string $ruleScope): self
{
if (
$ruleScope !== null
&& !in_array($ruleScope, [FirewallRuleObject::SCOPE_TENANT, FirewallRuleObject::SCOPE_SYSTEM], true)
) {
throw new \InvalidArgumentException("Invalid firewall rule scope: {$ruleScope}");
}
$this->ruleScope = $ruleScope;
return $this;
}
public function getIdentityId(): ?string
{
return $this->identityId;
@@ -11,6 +11,9 @@ use KTXF\Json\JsonDeserializable;
*/
class FirewallRuleObject implements \JsonSerializable, JsonDeserializable
{
public const SCOPE_TENANT = 'tenant';
public const SCOPE_SYSTEM = 'system';
public const TYPE_IP = 'ip';
public const TYPE_IP_RANGE = 'ip_range';
public const TYPE_DEVICE = 'device';
@@ -19,6 +22,7 @@ class FirewallRuleObject implements \JsonSerializable, JsonDeserializable
public const ACTION_BLOCK = 'block';
private ?string $id = null;
private string $scope = self::SCOPE_TENANT;
private ?string $tenantId = null;
private ?string $type = null; // ip, ip_range, device
private ?string $action = null; // allow, block
@@ -42,6 +46,10 @@ class FirewallRuleObject implements \JsonSerializable, JsonDeserializable
$this->id = $data['id'] !== null ? (string)$data['id'] : null;
}
if (!array_key_exists('scope', $data)) {
throw new \InvalidArgumentException('Firewall rules require an explicit scope.');
}
$this->setScope((string)$data['scope']);
if (array_key_exists('tenantId', $data)) {
$this->tenantId = $data['tenantId'] !== null ? (string)$data['tenantId'] : null;
}
@@ -61,14 +69,10 @@ class FirewallRuleObject implements \JsonSerializable, JsonDeserializable
$this->createdBy = $data['createdBy'] !== null ? (string)$data['createdBy'] : null;
}
if (array_key_exists('createdAt', $data)) {
$this->createdAt = $data['createdAt'] !== null
? new \DateTimeImmutable($data['createdAt'])
: null;
$this->createdAt = self::deserializeDate($data['createdAt']);
}
if (array_key_exists('expiresAt', $data)) {
$this->expiresAt = $data['expiresAt'] !== null
? new \DateTimeImmutable($data['expiresAt'])
: null;
$this->expiresAt = self::deserializeDate($data['expiresAt']);
}
if (array_key_exists('enabled', $data)) {
$this->enabled = (bool)$data['enabled'];
@@ -84,6 +88,7 @@ class FirewallRuleObject implements \JsonSerializable, JsonDeserializable
{
return [
'id' => $this->id,
'scope' => $this->scope,
'tenantId' => $this->tenantId,
'type' => $this->type,
'action' => $this->action,
@@ -97,6 +102,24 @@ class FirewallRuleObject implements \JsonSerializable, JsonDeserializable
];
}
private static function deserializeDate(mixed $value): ?\DateTimeImmutable
{
if ($value === null) {
return null;
}
if ($value instanceof \MongoDB\BSON\UTCDateTime) {
return \DateTimeImmutable::createFromMutable($value->toDateTime());
}
if ($value instanceof \DateTimeImmutable) {
return $value;
}
if ($value instanceof \DateTimeInterface) {
return \DateTimeImmutable::createFromInterface($value);
}
return new \DateTimeImmutable((string)$value);
}
/**
* Check if this rule has expired
*/
@@ -134,6 +157,42 @@ class FirewallRuleObject implements \JsonSerializable, JsonDeserializable
return $this->tenantId;
}
public function getScope(): string
{
return $this->scope;
}
public function setScope(string $scope): self
{
if (!in_array($scope, [self::SCOPE_TENANT, self::SCOPE_SYSTEM], true)) {
throw new \InvalidArgumentException("Invalid firewall rule scope: {$scope}");
}
$this->scope = $scope;
return $this;
}
public function isTenantScoped(): bool
{
return $this->scope === self::SCOPE_TENANT;
}
public function isSystemScoped(): bool
{
return $this->scope === self::SCOPE_SYSTEM;
}
public function assertValidScopeOwnership(): void
{
if ($this->isTenantScoped() && ($this->tenantId === null || $this->tenantId === '')) {
throw new \InvalidArgumentException('Tenant firewall rules require a tenant ID.');
}
if ($this->isSystemScoped() && $this->tenantId !== null) {
throw new \InvalidArgumentException('System firewall rules cannot have a tenant ID.');
}
}
public function setTenantId(?string $tenantId): self
{
$this->tenantId = $tenantId;
@@ -11,11 +11,17 @@ class TenantConfiguration extends JsonSerializableObject
{
protected TenantAuthentication $authentication;
protected TenantSecurity $security;
protected TenantFirewall $firewall;
protected TenantStores $stores;
protected TenantPreview $preview;
public function __construct()
{
$this->authentication = new TenantAuthentication();
$this->security = new TenantSecurity();
$this->firewall = new TenantFirewall();
$this->stores = new TenantStores();
$this->preview = new TenantPreview();
}
public function authentication(): TenantAuthentication {
@@ -26,4 +32,16 @@ class TenantConfiguration extends JsonSerializableObject
return $this->security;
}
public function firewall(): TenantFirewall {
return $this->firewall;
}
public function stores(): TenantStores {
return $this->stores;
}
public function preview(): TenantPreview {
return $this->preview;
}
}
+35
View File
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace KTXC\Models\Tenant;
use KTXF\Json\JsonSerializableObject;
class TenantFirewall extends JsonSerializableObject
{
protected bool $enabled = true;
protected int $maxAuthFailures = 5;
protected int $authFailureWindow = 300;
protected int $autoBlockDuration = 3600;
public function enabled(): bool
{
return $this->enabled;
}
public function maxAuthFailures(): int
{
return $this->maxAuthFailures;
}
public function authFailureWindow(): int
{
return $this->authFailureWindow;
}
public function autoBlockDuration(): int
{
return $this->autoBlockDuration;
}
}
+82
View File
@@ -0,0 +1,82 @@
<?php
declare(strict_types=1);
namespace KTXC\Models\Tenant;
use InvalidArgumentException;
use KTXF\Json\JsonSerializableObject;
final class TenantPreview extends JsonSerializableObject
{
protected bool $enabled = true;
protected string $store = 'previews';
protected int $maxSourceSize = 26214400;
protected TenantPreviewVariants $variants;
public function __construct()
{
$this->variants = new TenantPreviewVariants();
}
public function jsonDeserialize(array|string $data): static
{
if (is_string($data)) {
$data = json_decode($data, true, flags: JSON_THROW_ON_ERROR);
}
if (array_key_exists('enabled', $data)) {
if (!is_bool($data['enabled'])) {
throw new InvalidArgumentException('Preview enabled must be a boolean');
}
$this->enabled = $data['enabled'];
}
if (array_key_exists('store', $data)) {
if (!is_string($data['store']) || preg_match('/^[a-z][a-z0-9-]*$/', $data['store']) !== 1) {
throw new InvalidArgumentException('Preview store must be a logical system-store name');
}
$this->store = $data['store'];
}
if (array_key_exists('maxSourceSize', $data)) {
if (!is_int($data['maxSourceSize']) || $data['maxSourceSize'] < 1) {
throw new InvalidArgumentException('Preview maximum source size must be a positive integer');
}
$this->maxSourceSize = $data['maxSourceSize'];
}
if (array_key_exists('variants', $data)) {
if (!is_array($data['variants'])) {
throw new InvalidArgumentException('Preview variants configuration must be an object');
}
$this->variants->jsonDeserialize($data['variants']);
}
if ($this->enabled && $this->variants->all() === []) {
throw new InvalidArgumentException('At least one preview variant is required when previews are enabled');
}
return $this;
}
public function enabled(): bool
{
return $this->enabled;
}
public function store(): string
{
return $this->store;
}
public function maxSourceSize(): int
{
return $this->maxSourceSize;
}
public function variants(): TenantPreviewVariants
{
return $this->variants;
}
}
@@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
namespace KTXC\Models\Tenant;
use InvalidArgumentException;
use KTXF\Preview\MimeType;
final readonly class TenantPreviewVariant
{
public string $format;
public function __construct(
public int $width,
public int $height,
string $format,
public int $quality,
) {
if ($this->width < 1 || $this->height < 1) {
throw new InvalidArgumentException('Preview variant dimensions must be positive');
}
if ($this->quality < 1 || $this->quality > 100) {
throw new InvalidArgumentException('Preview variant quality must be between 1 and 100');
}
$this->format = MimeType::normalize($format);
}
public static function fromArray(array $data, ?self $defaults = null): self
{
$width = $data['width'] ?? $defaults?->width;
$height = $data['height'] ?? $defaults?->height;
$format = $data['format'] ?? $defaults?->format;
$quality = $data['quality'] ?? $defaults?->quality;
if (!is_int($width) || !is_int($height) || !is_string($format) || !is_int($quality)) {
throw new InvalidArgumentException('Preview variants require integer dimensions and quality plus a MIME format');
}
return new self($width, $height, $format, $quality);
}
/** @return array{width:int,height:int,format:string,quality:int} */
public function toArray(): array
{
return [
'width' => $this->width,
'height' => $this->height,
'format' => $this->format,
'quality' => $this->quality,
];
}
}
@@ -0,0 +1,70 @@
<?php
declare(strict_types=1);
namespace KTXC\Models\Tenant;
use InvalidArgumentException;
use KTXF\Json\JsonSerializableObject;
final class TenantPreviewVariants extends JsonSerializableObject
{
/** @var array<string, TenantPreviewVariant> */
private array $entries;
public function __construct()
{
$this->entries = self::defaults();
}
public function jsonDeserialize(array|string $data): static
{
if (is_string($data)) {
$data = json_decode($data, true, flags: JSON_THROW_ON_ERROR);
}
$defaults = self::defaults();
$entries = [];
foreach ($data as $name => $variant) {
if (!is_string($name) || preg_match('/^[a-z][a-z0-9-]*$/', $name) !== 1) {
throw new InvalidArgumentException('Invalid preview variant name');
}
if (!is_array($variant)) {
throw new InvalidArgumentException('Preview variant configuration must be an object');
}
$entries[$name] = TenantPreviewVariant::fromArray($variant, $defaults[$name] ?? null);
}
$this->entries = $entries;
return $this;
}
public function variant(string $name): ?TenantPreviewVariant
{
return $this->entries[$name] ?? null;
}
/** @return array<string, TenantPreviewVariant> */
public function all(): array
{
return $this->entries;
}
public function jsonSerialize(): array
{
return array_map(
static fn(TenantPreviewVariant $variant): array => $variant->toArray(),
$this->entries,
);
}
/** @return array<string, TenantPreviewVariant> */
private static function defaults(): array
{
return [
'thumbnail' => new TenantPreviewVariant(128, 128, 'image/webp', 70),
'inline' => new TenantPreviewVariant(640, 640, 'image/webp', 80),
'fullscreen' => new TenantPreviewVariant(2560, 2560, 'image/webp', 90),
];
}
}
+57
View File
@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace KTXC\Models\Tenant;
use InvalidArgumentException;
use KTXF\Json\JsonSerializableObject;
use KTXF\SystemStore\StoreReference;
/**
* Logical system stores configured for a tenant.
*/
final class TenantStores extends JsonSerializableObject
{
/** @var array<string, StoreReference> */
private array $entries = [];
public function jsonDeserialize(array|string $data): static
{
if (is_string($data)) {
$data = json_decode($data, true);
}
$this->entries = [];
foreach ($data as $name => $store) {
if (!is_string($name) || preg_match('/^[a-z][a-z0-9-]*$/', $name) !== 1) {
throw new InvalidArgumentException('Invalid logical system-store name');
}
if (!is_array($store)) {
throw new InvalidArgumentException('Invalid tenant store configuration entry');
}
$this->entries[$name] = StoreReference::fromArray($store);
}
return $this;
}
public function jsonSerialize(): array
{
return array_map(
static fn(StoreReference $store): array => $store->toArray(),
$this->entries,
);
}
public function store(string $name): ?StoreReference
{
return $this->entries[$name] ?? null;
}
/** @return array<string, StoreReference> */
public function all(): array
{
return $this->entries;
}
}
+98 -9
View File
@@ -2,10 +2,29 @@
namespace KTXC\Module;
use KTXC\Console\Firewall\FirewallMaintenanceCommand;
use KTXC\Console\Firewall\FirewallSetupCommand;
use KTXC\Service\FirewallService;
use KTXC\Service\SystemFirewallLogService;
use KTXC\Service\SystemFirewallRuleService;
use KTXC\Service\SystemFirewallStatusService;
use KTXC\Service\TenantFirewallLogService;
use KTXC\Service\TenantFirewallRuleService;
use KTXC\Service\TenantFirewallStatusService;
use KTXC\Security\Event\AccessDeniedEvent;
use KTXC\Security\Event\AuthenticationFailedEvent;
use KTXC\Security\Event\AuthenticationSucceededEvent;
use KTXC\Security\Event\BruteForceDetectedEvent;
use KTXC\Security\Event\FirewallRuleCreatedEvent;
use KTXC\Security\Event\FirewallRuleDisabledEvent;
use KTXC\Security\Event\FirewallRuleEnabledEvent;
use KTXC\Security\Event\FirewallRuleExtendedEvent;
use KTXC\Security\Event\FirewallRuleRemovedEvent;
use KTXC\Security\Event\FirewallSettingsUpdatedEvent;
use KTXC\Security\Event\RateLimitExceededEvent;
use KTXC\Security\Event\SuspiciousActivityEvent;
use KTXF\Event\DeliveryMode;
use KTXF\Event\EventListenerRegistry;
use KTXF\Event\SecurityEvent;
use KTXF\Event\EventListenerRegistrarInterface;
use KTXF\Module\ModuleBrowserInterface;
use KTXF\Module\ModuleConsoleInterface;
use KTXF\Module\ModuleInstanceAbstract;
@@ -18,7 +37,7 @@ use KTXF\Module\ModuleInstanceAbstract;
class Module extends ModuleInstanceAbstract implements ModuleConsoleInterface, ModuleBrowserInterface
{
public function __construct(
private readonly EventListenerRegistry $events,
private readonly EventListenerRegistrarInterface $events,
) {
}
@@ -26,17 +45,32 @@ class Module extends ModuleInstanceAbstract implements ModuleConsoleInterface, M
{
$this->events->listen(
'core',
SecurityEvent::AUTH_FAILURE,
AuthenticationFailedEvent::class,
FirewallService::class,
'handleAuthFailure',
DeliveryMode::Immediate,
priority: 100,
);
$this->events->listen(
'core',
AuthenticationSucceededEvent::class,
FirewallService::class,
'logAuthenticationSuccess',
DeliveryMode::Deferred,
);
foreach ([
SecurityEvent::AUTH_FAILURE,
SecurityEvent::AUTH_SUCCESS,
SecurityEvent::ACCESS_DENIED,
SecurityEvent::BRUTE_FORCE_DETECTED,
AccessDeniedEvent::class,
BruteForceDetectedEvent::class,
RateLimitExceededEvent::class,
SuspiciousActivityEvent::class,
FirewallRuleCreatedEvent::class,
FirewallRuleExtendedEvent::class,
FirewallRuleEnabledEvent::class,
FirewallRuleDisabledEvent::class,
FirewallRuleRemovedEvent::class,
FirewallSettingsUpdatedEvent::class,
] as $event) {
$this->events->listen(
'core',
@@ -115,7 +149,57 @@ class Module extends ModuleInstanceAbstract implements ModuleConsoleInterface, M
'group' => 'Module Management'
],
// System Administration
// Firewall Management
TenantFirewallRuleService::PERMISSION_READ => [
'label' => 'View Tenant Firewall Rules',
'description' => 'View firewall rules owned by the current tenant',
'group' => 'Firewall Management'
],
TenantFirewallRuleService::PERMISSION_MANAGE => [
'label' => 'Manage Tenant Firewall Rules',
'description' => 'Create, disable, and remove firewall rules owned by the current tenant',
'group' => 'Firewall Management'
],
TenantFirewallLogService::PERMISSION_READ => [
'label' => 'View Tenant Firewall Logs',
'description' => 'View firewall security and audit logs owned by the current tenant',
'group' => 'Firewall Management'
],
TenantFirewallStatusService::PERMISSION_SETTINGS_READ => [
'label' => 'View Tenant Firewall Settings',
'description' => 'View effective firewall settings for the current tenant',
'group' => 'Firewall Management'
],
TenantFirewallStatusService::PERMISSION_SETTINGS_MANAGE => [
'label' => 'Manage Tenant Firewall Settings',
'description' => 'Update firewall settings for the current tenant',
'group' => 'Firewall Management'
],
SystemFirewallRuleService::PERMISSION_READ => [
'label' => 'View System Firewall Rules',
'description' => 'View firewall rules that apply to every tenant',
'group' => 'System Administration'
],
SystemFirewallRuleService::PERMISSION_MANAGE => [
'label' => 'Manage System Firewall Rules',
'description' => 'Create, disable, and remove firewall rules that apply to every tenant',
'group' => 'System Administration'
],
SystemFirewallLogService::PERMISSION_READ => [
'label' => 'View System Firewall Logs',
'description' => 'View firewall security and audit logs across tenants',
'group' => 'System Administration'
],
SystemFirewallStatusService::PERMISSION_MAINTENANCE_READ => [
'label' => 'View Firewall Maintenance Status',
'description' => 'View the last firewall cleanup result and operational status',
'group' => 'System Administration'
],
SystemFirewallStatusService::PERMISSION_SETTINGS_MANAGE => [
'label' => 'Manage Tenant Firewall Settings System-Wide',
'description' => 'Update firewall settings for any tenant',
'group' => 'System Administration'
],
'system.admin' => [
'label' => 'System Administrator',
'description' => 'Full system access (superuser)',
@@ -132,6 +216,8 @@ class Module extends ModuleInstanceAbstract implements ModuleConsoleInterface, M
public function registerCI(): array
{
return [
FirewallSetupCommand::class,
FirewallMaintenanceCommand::class,
\KTXC\Console\Event\EventsDebugCommand::class,
\KTXC\Console\Module\ModuleListCommand::class,
\KTXC\Console\Module\ModuleEnableCommand::class,
@@ -143,6 +229,9 @@ class Module extends ModuleInstanceAbstract implements ModuleConsoleInterface, M
\KTXC\Console\Tenant\TenantListCommand::class,
\KTXC\Console\Tenant\TenantDeleteCommand::class,
\KTXC\Console\Tenant\TenantAuthEnableCommand::class,
\KTXC\Console\Tenant\TenantStoreListCommand::class,
\KTXC\Console\Tenant\TenantStoreSetCommand::class,
\KTXC\Console\Tenant\TenantStoreRemoveCommand::class,
\KTXC\Console\User\UserCreateCommand::class,
\KTXC\Console\User\UserListCommand::class,
\KTXC\Console\User\UserDeleteCommand::class,
+19
View File
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace KTXC\Preview;
use KTXF\Resource\BinaryResource;
final readonly class Preview
{
public function __construct(
public BinaryResource $resource,
public int $size,
public string $etag,
public ?int $width = null,
public ?int $height = null,
) {
}
}
+249
View File
@@ -0,0 +1,249 @@
<?php
declare(strict_types=1);
namespace KTXC\Preview;
use InvalidArgumentException;
use KTXC\Resource\ProviderManager;
use KTXC\Service\TenantService;
use KTXC\SystemStore\SystemStoreManager;
use KTXF\Preview\MimeType;
use KTXF\Preview\PreviewGenerationException;
use KTXF\Preview\PreviewRequest;
use KTXF\Preview\PreviewResult;
use KTXF\Preview\PreviewSource;
use KTXF\Preview\Provider\PreviewProviderInterface;
use KTXF\Resource\Provider\ProviderInterface;
use KTXF\SystemStore\BlobInfo;
use Psr\Log\LoggerInterface;
use Throwable;
final readonly class PreviewManager
{
public function __construct(
private TenantService $tenants,
private ProviderManager $providers,
private SystemStoreManager $stores,
private LoggerInterface $logger,
) {
}
public function fetch(
string $tenantId,
PreviewSource $source,
string $variant = 'inline',
): ?Preview {
$tenant = $this->tenants->fetchById($tenantId);
if ($tenant === null) {
return null;
}
$configuration = $tenant->getConfiguration()->preview();
$variantConfiguration = $configuration->variants()->variant($variant);
if (
!$configuration->enabled()
|| $variantConfiguration === null
|| ($source->size !== null && $source->size > $configuration->maxSourceSize())
) {
return null;
}
$request = new PreviewRequest(
maxWidth: $variantConfiguration->width,
maxHeight: $variantConfiguration->height,
preferredMimeType: $variantConfiguration->format,
quality: $variantConfiguration->quality,
maxSourceSize: $configuration->maxSourceSize(),
);
try {
$cached = $this->readCache(
$tenantId,
$configuration->store(),
$source,
$request,
);
if ($cached !== null) {
return $cached;
}
$provider = $this->selectProvider($source->mimeType, $request);
$result = $provider->generate($source, $request);
$blob = $this->writeCache(
$tenantId,
$configuration->store(),
$source,
$request,
$result,
);
return $this->readStoredPreview(
$tenantId,
$configuration->store(),
$blob,
$request,
);
} catch (Throwable $exception) {
$this->logger->warning('Preview unavailable', [
'tenantId' => $tenantId,
'sourceType' => $source->sourceType,
'variant' => $variant,
'exception' => $exception,
]);
return null;
}
}
private function readCache(
string $tenantId,
string $store,
PreviewSource $source,
PreviewRequest $request,
): ?Preview {
$key = $this->cacheKey($tenantId, $source, $request);
$blob = $this->stores->stat($tenantId, $store, $key);
if (!$this->validBlob($blob, $key, $request)) {
return null;
}
return $this->readStoredPreview($tenantId, $store, $blob, $request);
}
private function readStoredPreview(
string $tenantId,
string $store,
BlobInfo $blob,
PreviewRequest $request,
): ?Preview {
$resource = $this->stores->read($tenantId, $store, $blob->key);
if ($resource === null) {
return null;
}
try {
if (MimeType::normalize($resource->mimeType()) !== $request->preferredMimeType) {
return null;
}
} catch (Throwable) {
return null;
}
return new Preview(
resource: $resource,
size: $blob->size,
etag: $blob->etag,
width: $blob->attributes['width'] ?? null,
height: $blob->attributes['height'] ?? null,
);
}
private function writeCache(
string $tenantId,
string $store,
PreviewSource $source,
PreviewRequest $request,
PreviewResult $result,
): BlobInfo {
$outputMimeType = MimeType::normalize($result->resource->mimeType());
if ($outputMimeType !== $request->preferredMimeType) {
throw new PreviewGenerationException('Generated preview MIME does not match the requested output MIME');
}
if (
($result->width !== null && $result->width > $request->maxWidth)
|| ($result->height !== null && $result->height > $request->maxHeight)
) {
throw new PreviewGenerationException('Generated preview dimensions exceed the requested limits');
}
return $this->stores->write(
$tenantId,
$store,
$this->cacheKey($tenantId, $source, $request),
$result->resource,
['width' => $result->width, 'height' => $result->height],
);
}
private function cacheKey(
string $tenantId,
PreviewSource $source,
PreviewRequest $request,
): string {
if (trim($tenantId) === '') {
throw new InvalidArgumentException('Preview cache keys require a tenant identifier');
}
$canonical = json_encode([
'tenantId' => $tenantId,
'source' => [
'type' => $source->sourceType,
'identity' => $source->identity,
'signature' => $source->signature,
'mimeType' => $source->mimeType,
],
'request' => [
'maxWidth' => $request->maxWidth,
'maxHeight' => $request->maxHeight,
'preferredMimeType' => $request->preferredMimeType,
'quality' => $request->quality,
],
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION);
$digest = hash('sha256', $canonical);
return "generated/{$source->sourceType}/" . substr($digest, 0, 2) . "/{$digest}";
}
private function validBlob(?BlobInfo $blob, string $key, PreviewRequest $request): bool
{
if ($blob === null || $blob->key !== $key || $blob->size < 1) {
return false;
}
$width = $blob->attributes['width'] ?? null;
$height = $blob->attributes['height'] ?? null;
if (
($width !== null && (!is_int($width) || $width < 1 || $width > $request->maxWidth))
|| ($height !== null && (!is_int($height) || $height < 1 || $height > $request->maxHeight))
) {
return false;
}
try {
return MimeType::normalize($blob->mimeType) === $request->preferredMimeType;
} catch (Throwable) {
return false;
}
}
private function selectProvider(
string $sourceMimeType,
PreviewRequest $request,
): PreviewProviderInterface {
$sourceMimeType = MimeType::normalize($sourceMimeType);
$candidates = [];
foreach ($this->providers->providers(ProviderInterface::TYPE_PREVIEW) as $identifier => $provider) {
if (
!$provider instanceof PreviewProviderInterface
|| !$provider->supports($sourceMimeType, $request)
) {
continue;
}
$candidates[] = ['identifier' => $identifier, 'provider' => $provider];
}
if ($candidates === []) {
throw new PreviewGenerationException(
"No preview provider supports {$sourceMimeType} to {$request->preferredMimeType}"
);
}
usort($candidates, static function (array $left, array $right): int {
return ($right['provider']->priority() <=> $left['provider']->priority())
?: strcmp($left['identifier'], $right['identifier']);
});
return $candidates[0]['provider'];
}
}
+26 -17
View File
@@ -11,6 +11,7 @@ use KTXC\Http\Middleware\MiddlewarePipeline;
use KTXC\Http\Middleware\RouterMiddleware;
use KTXC\Http\Middleware\TenantMiddleware;
use KTXC\Http\Request\Request;
use KTXC\Http\Request\RequestContext;
use KTXC\Http\Response\Response;
use KTXC\KernelInterface;
@@ -25,26 +26,34 @@ final class HttpRuntime
public function run(?Request $request = null, bool $send = true): Response
{
$request ??= Request::createFromGlobals();
$requestContext = null;
return $this->kernel->executionRunner()->execute(
ExecutionDescriptor::http(),
function () use ($request, $send): Response {
$response = $this->pipeline()->handle($request);
if ($send) {
$response->send();
}
try {
return $this->kernel->executionRunner()->execute(
ExecutionDescriptor::http(),
function () use ($request, $send, &$requestContext): Response {
$requestContext = $this->kernel->container()->get(RequestContext::class);
$requestContext->initialize($request);
return $response;
},
function (\Throwable $error) use ($send): Response {
$response = $this->errorResponse($error);
if ($send) {
$response->send();
}
$response = $this->pipeline()->handle($request);
if ($send) {
$response->send();
}
return $response;
},
);
return $response;
},
function (\Throwable $error) use ($send): Response {
$response = $this->errorResponse($error);
if ($send) {
$response->send();
}
return $response;
},
);
} finally {
$requestContext?->clear();
}
}
private function pipeline(): MiddlewarePipeline
+38 -1
View File
@@ -8,11 +8,14 @@ use KTXC\Models\Identity\User;
use KTXC\Resource\ProviderManager;
use KTXC\Security\Authentication\AuthenticationRequest;
use KTXC\Security\Authentication\AuthenticationResponse;
use KTXC\Security\Event\AuthenticationFailedEvent;
use KTXC\Security\Event\AuthenticationSucceededEvent;
use KTXC\Service\TokenService;
use KTXC\Service\UserAccountsService;
use KTXC\Context\TenantContextInterface;
use KTXF\Cache\CacheScope;
use KTXF\Cache\EphemeralCacheInterface;
use KTXF\Event\EventDispatcherInterface;
use KTXF\Security\Authentication\AuthenticationProviderInterface;
use KTXF\Security\Authentication\AuthenticationSession;
use KTXF\Security\Authentication\ProviderContext;
@@ -31,6 +34,7 @@ class AuthenticationManager
private readonly ProviderManager $providerManager,
private readonly TokenService $tokenService,
private readonly UserAccountsService $userService,
private readonly EventDispatcherInterface $events,
) {
$this->securityCode = $this->tenantContext->configuration()->security()->code();
}
@@ -187,6 +191,10 @@ class AuthenticationManager
if (!$result->isSuccess()) {
$this->saveSession($session);
$this->publishAuthenticationFailure(
$session,
$result->errorCode ?? AuthenticationResponse::ERROR_INVALID_CREDENTIALS,
);
return AuthenticationResponse::failed(
AuthenticationResponse::ERROR_INVALID_CREDENTIALS,
'Authentication failed. If you haven\'t set up this method, try another option.',
@@ -389,6 +397,10 @@ class AuthenticationManager
$result = $provider->completeRedirect($context, $request->params);
if ($result->isFailed()) {
$this->publishAuthenticationFailure(
$session,
$result->errorCode ?? AuthenticationResponse::ERROR_INVALID_CREDENTIALS,
);
$this->deleteSession($session->id);
return AuthenticationResponse::failed(
AuthenticationResponse::ERROR_INVALID_CREDENTIALS,
@@ -566,6 +578,17 @@ class AuthenticationManager
// Helper Methods
// =========================================================================
private function publishAuthenticationFailure(
AuthenticationSession $session,
string $reason,
): void {
$this->events->dispatch(new AuthenticationFailedEvent(
userId: $session->userIdentifier,
reason: $reason,
tenantId: $session->tenantIdentifier,
));
}
/**
* Build provider context from session
*/
@@ -594,7 +617,16 @@ class AuthenticationManager
*/
private function completeAuthentication(AuthenticationSession $session): AuthenticationResponse
{
$userData = $this->userService->fetchByIdentifier($session->userIdentifier);
$userId = $session->userIdentifier;
if ($userId === null) {
return AuthenticationResponse::failed(
AuthenticationResponse::ERROR_INVALID_SESSION,
'Authenticated user is missing',
401,
);
}
$userData = $this->userService->fetchByIdentifier($userId);
if ($userData === null) {
return AuthenticationResponse::failed(
@@ -611,6 +643,11 @@ class AuthenticationManager
$this->deleteSession($session->id);
$this->events->dispatch(new AuthenticationSucceededEvent(
$userId,
$session->tenantIdentifier,
));
return AuthenticationResponse::success(
$this->buildUserData($user),
$tokens
@@ -0,0 +1,88 @@
<?php
declare(strict_types=1);
namespace KTXC\Security\Event;
use KTXC\Models\Firewall\FirewallRuleObject;
use KTXF\Event\Event;
final class AccessDeniedEvent extends Event implements SecurityRequestEventInterface
{
public function __construct(
private readonly string $ipAddress,
private readonly string $ruleId,
private readonly string $ruleScope,
private readonly ?string $deviceFingerprint = null,
private readonly ?string $reason = null,
?string $tenantId = null,
?string $identityId = null,
) {
if ($ipAddress === '') {
throw new \InvalidArgumentException('Access denial requires an IP address.');
}
if ($ruleId === '') {
throw new \InvalidArgumentException('Access denial requires a firewall rule ID.');
}
if (!in_array($ruleScope, [FirewallRuleObject::SCOPE_SYSTEM, FirewallRuleObject::SCOPE_TENANT], true)) {
throw new \InvalidArgumentException('Access denial requires a valid firewall rule scope.');
}
parent::__construct(
self::class,
['ruleId' => $ruleId, 'ruleScope' => $ruleScope, 'reason' => $reason],
$tenantId,
$identityId,
);
}
public function getIpAddress(): string
{
return $this->ipAddress;
}
public function getRuleId(): string
{
return $this->ruleId;
}
public function getRuleScope(): string
{
return $this->ruleScope;
}
public function getDeviceFingerprint(): ?string
{
return $this->deviceFingerprint;
}
public function getUserAgent(): ?string
{
return null;
}
public function getRequestPath(): ?string
{
return null;
}
public function getRequestMethod(): ?string
{
return null;
}
public function getUserId(): ?string
{
return null;
}
public function getReason(): ?string
{
return $this->reason;
}
public function getSeverity(): SecurityEventSeverity
{
return SecurityEventSeverity::WARNING;
}
}
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace KTXC\Security\Event;
use KTXF\Event\Event;
final class AuthenticationFailedEvent extends Event implements SecurityEventInterface
{
public function __construct(
private readonly ?string $userId = null,
private readonly ?string $reason = null,
?string $tenantId = null,
?string $identityId = null,
) {
parent::__construct(
self::class,
['userId' => $userId, 'reason' => $reason],
$tenantId,
$identityId,
);
}
public function getUserId(): ?string
{
return $this->userId;
}
public function getReason(): ?string
{
return $this->reason;
}
public function getSeverity(): SecurityEventSeverity
{
return SecurityEventSeverity::WARNING;
}
}
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace KTXC\Security\Event;
use KTXF\Event\Event;
final class AuthenticationSucceededEvent extends Event implements SecurityEventInterface
{
public function __construct(
private readonly string $userId,
?string $tenantId = null,
) {
if ($userId === '') {
throw new \InvalidArgumentException('Successful authentication requires a user ID.');
}
parent::__construct(
self::class,
['userId' => $userId],
$tenantId,
);
}
public function getUserId(): string
{
return $this->userId;
}
public function getReason(): ?string
{
return null;
}
public function getSeverity(): SecurityEventSeverity
{
return SecurityEventSeverity::INFO;
}
}
@@ -0,0 +1,91 @@
<?php
declare(strict_types=1);
namespace KTXC\Security\Event;
use KTXF\Event\Event;
final class BruteForceDetectedEvent extends Event implements SecurityRequestEventInterface
{
private readonly string $reason;
public function __construct(
private readonly string $ipAddress,
private readonly int $failureCount,
private readonly int $windowSeconds,
?string $tenantId = null,
) {
if ($ipAddress === '') {
throw new \InvalidArgumentException('Brute-force detection requires an IP address.');
}
if ($failureCount < 1) {
throw new \InvalidArgumentException('Brute-force detection requires at least one failure.');
}
if ($windowSeconds < 1) {
throw new \InvalidArgumentException('Brute-force detection requires a positive window.');
}
$this->reason = sprintf(
'%d failed attempts in %d seconds',
$failureCount,
$windowSeconds,
);
parent::__construct(
self::class,
['failureCount' => $failureCount, 'windowSeconds' => $windowSeconds],
$tenantId,
);
}
public function getIpAddress(): string
{
return $this->ipAddress;
}
public function getFailureCount(): int
{
return $this->failureCount;
}
public function getWindowSeconds(): int
{
return $this->windowSeconds;
}
public function getDeviceFingerprint(): ?string
{
return null;
}
public function getUserAgent(): ?string
{
return null;
}
public function getRequestPath(): ?string
{
return null;
}
public function getRequestMethod(): ?string
{
return null;
}
public function getUserId(): ?string
{
return null;
}
public function getReason(): string
{
return $this->reason;
}
public function getSeverity(): SecurityEventSeverity
{
return SecurityEventSeverity::CRITICAL;
}
}
@@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
namespace KTXC\Security\Event;
use KTXF\Event\Event;
final class DeviceBlockedEvent extends Event implements SecurityRequestEventInterface
{
public function __construct(
private readonly string $deviceFingerprint,
private readonly ?string $reason = null,
?string $tenantId = null,
) {
if ($deviceFingerprint === '') {
throw new \InvalidArgumentException('Device-block events require a fingerprint.');
}
parent::__construct(
self::class,
['device' => $deviceFingerprint, 'reason' => $reason],
$tenantId,
);
}
public function getIpAddress(): ?string
{
return null;
}
public function getDeviceFingerprint(): string
{
return $this->deviceFingerprint;
}
public function getUserAgent(): ?string
{
return null;
}
public function getRequestPath(): ?string
{
return null;
}
public function getRequestMethod(): ?string
{
return null;
}
public function getUserId(): ?string
{
return null;
}
public function getReason(): ?string
{
return $this->reason;
}
public function getSeverity(): SecurityEventSeverity
{
return SecurityEventSeverity::CRITICAL;
}
}
@@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
namespace KTXC\Security\Event;
use KTXF\Event\Event;
abstract class FirewallIpEvent extends Event implements SecurityRequestEventInterface
{
protected const SecurityEventSeverity SEVERITY = SecurityEventSeverity::INFO;
final public function __construct(
private readonly string $ipAddress,
private readonly ?string $reason = null,
?string $tenantId = null,
) {
if ($ipAddress === '') {
throw new \InvalidArgumentException('Firewall IP events require an IP address.');
}
parent::__construct(
static::class,
['ip' => $ipAddress, 'reason' => $reason],
$tenantId,
);
}
public function getIpAddress(): string
{
return $this->ipAddress;
}
public function getDeviceFingerprint(): ?string
{
return null;
}
public function getUserAgent(): ?string
{
return null;
}
public function getRequestPath(): ?string
{
return null;
}
public function getRequestMethod(): ?string
{
return null;
}
public function getUserId(): ?string
{
return null;
}
public function getReason(): ?string
{
return $this->reason;
}
public function getSeverity(): SecurityEventSeverity
{
return static::SEVERITY;
}
}
@@ -0,0 +1,9 @@
<?php
declare(strict_types=1);
namespace KTXC\Security\Event;
final class FirewallRuleCreatedEvent extends FirewallRuleEvent
{
}
@@ -0,0 +1,9 @@
<?php
declare(strict_types=1);
namespace KTXC\Security\Event;
final class FirewallRuleDisabledEvent extends FirewallRuleEvent
{
}
@@ -0,0 +1,9 @@
<?php
declare(strict_types=1);
namespace KTXC\Security\Event;
final class FirewallRuleEnabledEvent extends FirewallRuleEvent
{
}
@@ -0,0 +1,158 @@
<?php
declare(strict_types=1);
namespace KTXC\Security\Event;
use KTXC\Models\Firewall\FirewallRuleObject;
use KTXF\Event\Event;
abstract class FirewallRuleEvent extends Event implements SecurityEventInterface
{
final protected function __construct(
private readonly string $ruleId,
private readonly string $ruleScope,
private readonly string $ruleType,
private readonly string $ruleAction,
private readonly string $ruleValue,
private readonly ?string $reason,
private readonly string $origin,
private readonly ?string $expiresAt,
private readonly array $details,
?string $tenantId,
?string $identityId,
) {
if ($ruleId === '') {
throw new \InvalidArgumentException('Firewall rule events require a rule ID.');
}
foreach ([
'scope' => $ruleScope,
'type' => $ruleType,
'action' => $ruleAction,
'value' => $ruleValue,
'origin' => $origin,
] as $field => $value) {
if ($value === '') {
throw new \InvalidArgumentException("Firewall rule events require a rule {$field}.");
}
}
foreach ([
'scope' => $ruleScope,
'type' => $ruleType,
'action' => $ruleAction,
'value' => $ruleValue,
'origin' => $origin,
] as $field => $value) {
if ($value === '') {
throw new \InvalidArgumentException("Firewall rule events require a rule {$field}.");
}
}
parent::__construct(
static::class,
[
'ruleId' => $ruleId,
'ruleScope' => $ruleScope,
'ruleType' => $ruleType,
'ruleAction' => $ruleAction,
'ruleValue' => $ruleValue,
'reason' => $reason,
'origin' => $origin,
'expiresAt' => $expiresAt,
...$details,
],
$tenantId,
$identityId,
);
}
public static function fromRule(
FirewallRuleObject $rule,
?string $actorId = null,
array $change = [],
): static {
$metadata = $rule->getMetadata() ?? [];
$details = [...$metadata, ...$change];
foreach ([
'ruleId',
'ruleScope',
'ruleType',
'ruleAction',
'ruleValue',
'reason',
'origin',
'expiresAt',
] as $reservedKey) {
unset($details[$reservedKey]);
}
return new static(
ruleId: (string) $rule->getId(),
ruleScope: (string) $rule->getScope(),
ruleType: (string) $rule->getType(),
ruleAction: (string) $rule->getAction(),
ruleValue: (string) $rule->getValue(),
reason: $rule->getReason(),
origin: (string) ($metadata['origin'] ?? 'manual'),
expiresAt: $rule->getExpiresAt()?->format(\DateTimeInterface::ATOM),
details: $details,
tenantId: $rule->getTenantId(),
identityId: $actorId ?? $rule->getCreatedBy(),
);
}
public function getRuleId(): string
{
return $this->ruleId;
}
public function getRuleScope(): string
{
return $this->ruleScope;
}
public function getRuleType(): string
{
return $this->ruleType;
}
public function getRuleAction(): string
{
return $this->ruleAction;
}
public function getRuleValue(): string
{
return $this->ruleValue;
}
public function getOrigin(): string
{
return $this->origin;
}
public function getExpiresAt(): ?string
{
return $this->expiresAt;
}
public function getDetails(): array
{
return $this->details;
}
public function getUserId(): ?string
{
return null;
}
public function getReason(): ?string
{
return $this->reason;
}
public function getSeverity(): SecurityEventSeverity
{
return SecurityEventSeverity::INFO;
}
}
@@ -0,0 +1,9 @@
<?php
declare(strict_types=1);
namespace KTXC\Security\Event;
final class FirewallRuleExtendedEvent extends FirewallRuleEvent
{
}
@@ -0,0 +1,9 @@
<?php
declare(strict_types=1);
namespace KTXC\Security\Event;
final class FirewallRuleRemovedEvent extends FirewallRuleEvent
{
}
@@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
namespace KTXC\Security\Event;
use KTXF\Event\Event;
final class FirewallSettingsUpdatedEvent extends Event implements SecurityEventInterface
{
public function __construct(
private readonly string $changeReason,
private readonly array $previous,
private readonly array $current,
string $tenantId,
?string $actorId = null,
private readonly string $changeOrigin = 'manual',
) {
if ($changeReason === '') {
throw new \InvalidArgumentException('Firewall settings updates require a change reason.');
}
if ($tenantId === '') {
throw new \InvalidArgumentException('Firewall settings updates require a tenant ID.');
}
if ($changeOrigin === '') {
throw new \InvalidArgumentException('Firewall settings updates require a change origin.');
}
parent::__construct(
self::class,
[
'changeReason' => $changeReason,
'changeOrigin' => $changeOrigin,
'previous' => $previous,
'current' => $current,
],
$tenantId,
$actorId,
);
}
public function getChangeReason(): string
{
return $this->changeReason;
}
public function getPrevious(): array
{
return $this->previous;
}
public function getCurrent(): array
{
return $this->current;
}
public function getChangeOrigin(): string
{
return $this->changeOrigin;
}
public function getUserId(): ?string
{
return null;
}
public function getReason(): string
{
return $this->changeReason;
}
public function getSeverity(): SecurityEventSeverity
{
return SecurityEventSeverity::INFO;
}
}
@@ -0,0 +1,9 @@
<?php
declare(strict_types=1);
namespace KTXC\Security\Event;
final class IpAllowedEvent extends FirewallIpEvent
{
}
@@ -0,0 +1,10 @@
<?php
declare(strict_types=1);
namespace KTXC\Security\Event;
final class IpBlockedEvent extends FirewallIpEvent
{
protected const SecurityEventSeverity SEVERITY = SecurityEventSeverity::CRITICAL;
}
@@ -0,0 +1,104 @@
<?php
declare(strict_types=1);
namespace KTXC\Security\Event;
use KTXF\Event\Event;
final class RateLimitExceededEvent extends Event implements SecurityRequestEventInterface
{
private readonly string $reason;
public function __construct(
private readonly string $ipAddress,
private readonly int $requestCount,
private readonly int $windowSeconds,
private readonly ?string $endpoint = null,
?string $tenantId = null,
) {
if ($ipAddress === '') {
throw new \InvalidArgumentException('Rate-limit detection requires an IP address.');
}
if ($requestCount < 1) {
throw new \InvalidArgumentException('Rate-limit detection requires at least one request.');
}
if ($windowSeconds < 1) {
throw new \InvalidArgumentException('Rate-limit detection requires a positive window.');
}
if ($endpoint === '') {
throw new \InvalidArgumentException('A supplied rate-limit endpoint cannot be empty.');
}
$this->reason = sprintf(
'%d requests in %d seconds',
$requestCount,
$windowSeconds,
);
parent::__construct(
self::class,
[
'requestCount' => $requestCount,
'windowSeconds' => $windowSeconds,
'endpoint' => $endpoint,
],
$tenantId,
);
}
public function getIpAddress(): string
{
return $this->ipAddress;
}
public function getRequestCount(): int
{
return $this->requestCount;
}
public function getWindowSeconds(): int
{
return $this->windowSeconds;
}
public function getEndpoint(): ?string
{
return $this->endpoint;
}
public function getDeviceFingerprint(): ?string
{
return null;
}
public function getUserAgent(): ?string
{
return null;
}
public function getRequestPath(): ?string
{
return $this->endpoint;
}
public function getRequestMethod(): ?string
{
return null;
}
public function getUserId(): ?string
{
return null;
}
public function getReason(): string
{
return $this->reason;
}
public function getSeverity(): SecurityEventSeverity
{
return SecurityEventSeverity::ERROR;
}
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace KTXC\Security\Event;
interface SecurityEventInterface
{
public function label(): string;
public function get(string $key, mixed $default = null): mixed;
public function context(): array;
public function identifier(): string;
public function tenantIdentifier(): ?string;
public function actorIdentity(): ?string;
public function getUserId(): ?string;
public function getReason(): ?string;
public function getSeverity(): SecurityEventSeverity;
}
@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace KTXC\Security\Event;
enum SecurityEventSeverity: int
{
case DEBUG = 0;
case INFO = 1;
case WARNING = 2;
case ERROR = 3;
case CRITICAL = 4;
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace KTXC\Security\Event;
interface SecurityRequestEventInterface extends SecurityEventInterface
{
public function getIpAddress(): ?string;
public function getDeviceFingerprint(): ?string;
public function getUserAgent(): ?string;
public function getRequestPath(): ?string;
public function getRequestMethod(): ?string;
}
@@ -0,0 +1,100 @@
<?php
declare(strict_types=1);
namespace KTXC\Security\Event;
use KTXF\Event\Event;
final class SuspiciousActivityEvent extends Event implements SecurityRequestEventInterface
{
public function __construct(
private readonly string $ipAddress,
private readonly string $detector,
private readonly array $detectionData = [],
?string $tenantId = null,
?string $identityId = null,
private readonly ?string $deviceFingerprint = null,
private readonly ?string $userAgent = null,
private readonly ?string $requestPath = null,
private readonly ?string $requestMethod = null,
private readonly ?string $userId = null,
private readonly ?string $reason = null,
) {
if ($ipAddress === '') {
throw new \InvalidArgumentException('Suspicious activity requires an IP address.');
}
if ($detector === '') {
throw new \InvalidArgumentException('Suspicious activity requires a detector.');
}
if (array_key_exists('detector', $detectionData)) {
throw new \InvalidArgumentException('Detection data cannot replace the detector.');
}
if (array_key_exists('detector', $detectionData)) {
throw new \InvalidArgumentException('Detection data cannot replace the detector.');
}
if ($requestPath === '') {
throw new \InvalidArgumentException('A supplied request path cannot be empty.');
}
if ($requestMethod === '') {
throw new \InvalidArgumentException('A supplied request method cannot be empty.');
}
parent::__construct(
self::class,
['detector' => $detector] + $detectionData,
$tenantId,
$identityId,
);
}
public function getIpAddress(): string
{
return $this->ipAddress;
}
public function getDetector(): string
{
return $this->detector;
}
public function getDetectionData(): array
{
return $this->detectionData;
}
public function getDeviceFingerprint(): ?string
{
return $this->deviceFingerprint;
}
public function getUserAgent(): ?string
{
return $this->userAgent;
}
public function getRequestPath(): ?string
{
return $this->requestPath;
}
public function getRequestMethod(): ?string
{
return $this->requestMethod;
}
public function getUserId(): ?string
{
return $this->userId;
}
public function getReason(): ?string
{
return $this->reason;
}
public function getSeverity(): SecurityEventSeverity
{
return SecurityEventSeverity::ERROR;
}
}
+126
View File
@@ -0,0 +1,126 @@
<?php
declare(strict_types=1);
namespace KTXC\Service;
use KTXC\Models\Firewall\FirewallLogObject;
use KTXC\Models\Firewall\FirewallRuleObject;
use KTXC\Stores\FirewallStore;
final class FirewallLogService
{
public const MAX_LIMIT = 100;
private const EVENT_TYPES = [
FirewallLogObject::EVENT_AUTH_FAILURE,
FirewallLogObject::EVENT_RATE_LIMIT,
FirewallLogObject::EVENT_BRUTE_FORCE,
FirewallLogObject::EVENT_SUSPICIOUS,
FirewallLogObject::EVENT_RULE_MATCH,
FirewallLogObject::EVENT_ACCESS_CHECK,
FirewallLogObject::EVENT_RULE_CREATED,
FirewallLogObject::EVENT_RULE_EXTENDED,
FirewallLogObject::EVENT_RULE_ENABLED,
FirewallLogObject::EVENT_RULE_DISABLED,
FirewallLogObject::EVENT_RULE_REMOVED,
FirewallLogObject::EVENT_SETTINGS_UPDATED,
];
public function __construct(private readonly FirewallStore $store)
{
}
public function tenant(string $tenantId, array $filters, int $limit, int $offset): array
{
return $this->store->queryTenantLogs(
$tenantId,
$this->validate($filters, $limit, $offset),
$limit,
$offset
);
}
public function system(?string $tenantId, array $filters, int $limit, int $offset): array
{
if ($tenantId !== null && ($tenantId === '' || strlen($tenantId) > 128)) {
throw new \InvalidArgumentException('Invalid tenant filter.');
}
return $this->store->querySystemLogs(
$tenantId,
$this->validate($filters, $limit, $offset),
$limit,
$offset
);
}
private function validate(array $filters, int $limit, int $offset): array
{
if ($limit < 1 || $limit > self::MAX_LIMIT || $offset < 0) {
throw new \InvalidArgumentException('Pagination requires limit 1-100 and offset 0 or greater.');
}
$ipAddress = self::nullableString($filters, 'ipAddress');
if ($ipAddress !== null && filter_var($ipAddress, FILTER_VALIDATE_IP) === false) {
throw new \InvalidArgumentException('Invalid IP address filter.');
}
$eventType = self::nullableString($filters, 'eventType');
if ($eventType !== null && !in_array($eventType, self::EVENT_TYPES, true)) {
throw new \InvalidArgumentException('Invalid firewall event type filter.');
}
$result = self::nullableString($filters, 'result');
if ($result !== null && !in_array($result, [
FirewallLogObject::RESULT_ALLOWED,
FirewallLogObject::RESULT_BLOCKED,
FirewallLogObject::RESULT_RECORDED,
], true)) {
throw new \InvalidArgumentException('Invalid firewall result filter.');
}
$ruleScope = self::nullableString($filters, 'ruleScope');
if ($ruleScope !== null && !in_array($ruleScope, [
FirewallRuleObject::SCOPE_TENANT,
FirewallRuleObject::SCOPE_SYSTEM,
], true)) {
throw new \InvalidArgumentException('Invalid rule scope filter.');
}
$from = self::date($filters, 'from');
$to = self::date($filters, 'to');
if ($from !== null && $to !== null && $from > $to) {
throw new \InvalidArgumentException('The from date must not be later than the to date.');
}
return [
'ipAddress' => $ipAddress,
'eventType' => $eventType,
'result' => $result,
'ruleId' => self::nullableString($filters, 'ruleId'),
'ruleScope' => $ruleScope,
'from' => $from,
'to' => $to,
];
}
private static function nullableString(array $filters, string $key): ?string
{
$value = $filters[$key] ?? null;
if ($value === null) {
return null;
}
if (!is_string($value) || $value === '' || strlen($value) > 255) {
throw new \InvalidArgumentException("Invalid {$key} filter.");
}
return $value;
}
private static function date(array $filters, string $key): ?\DateTimeImmutable
{
$value = self::nullableString($filters, $key);
if ($value === null) {
return null;
}
try {
return new \DateTimeImmutable($value);
} catch (\Exception) {
throw new \InvalidArgumentException("Invalid {$key} date filter.");
}
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace KTXC\Service;
use KTXC\Models\Firewall\FirewallRuleObject;
use KTXC\Stores\FirewallStore;
final class FirewallRuleCache
{
/** @var array<string, FirewallRuleObject[]> */
private array $tenantRules = [];
/** @var FirewallRuleObject[]|null */
private ?array $systemRules = null;
public function __construct(private readonly FirewallStore $store)
{
}
/** @return FirewallRuleObject[] */
public function tenant(string $tenantId): array
{
return $this->tenantRules[$tenantId] ??= $this->store->listRules($tenantId);
}
/** @return FirewallRuleObject[] */
public function system(): array
{
return $this->systemRules ??= $this->store->listSystemRules();
}
public function invalidate(): void
{
$this->tenantRules = [];
$this->systemRules = null;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace KTXC\Service;
final class FirewallRuleConflictException extends \RuntimeException
{
public function __construct(
public readonly string $conflictCode,
string $message
) {
parent::__construct($message);
}
}
+517
View File
@@ -0,0 +1,517 @@
<?php
declare(strict_types=1);
namespace KTXC\Service;
use KTXC\Models\Firewall\FirewallRuleObject;
use KTXC\Security\Event\FirewallRuleCreatedEvent;
use KTXC\Security\Event\FirewallRuleDisabledEvent;
use KTXC\Security\Event\FirewallRuleEnabledEvent;
use KTXC\Security\Event\FirewallRuleEvent;
use KTXC\Security\Event\FirewallRuleExtendedEvent;
use KTXC\Security\Event\FirewallRuleRemovedEvent;
use KTXC\Security\Event\DeviceBlockedEvent;
use KTXC\Security\Event\IpAllowedEvent;
use KTXC\Security\Event\IpBlockedEvent;
use KTXC\Stores\FirewallStore;
use KTXF\Event\EventDispatcherInterface;
use KTXF\IpUtils;
final class FirewallRuleManager
{
public const QUERY_STATUSES = ['active', 'disabled', 'expired', 'all'];
public const MAX_QUERY_LIMIT = 100;
public const ORIGIN_MANUAL = 'manual';
public const ORIGIN_AUTOMATIC = 'automatic';
public function __construct(
private readonly FirewallStore $store,
private readonly FirewallRuleCache $cache,
private readonly EventDispatcherInterface $events,
) {
}
public function list(FirewallRuleScope $scope, bool $activeOnly = true): array
{
return $scope->scope === FirewallRuleObject::SCOPE_SYSTEM
? $this->store->listSystemRules($activeOnly)
: $this->store->listRules($scope->tenantId, $activeOnly);
}
public function query(
FirewallRuleScope $scope,
string $status = 'active',
?string $type = null,
?string $action = null,
int $limit = 50,
int $offset = 0
): array {
if (!in_array($status, self::QUERY_STATUSES, true)) {
throw new \InvalidArgumentException('Invalid rule status filter.');
}
if ($type !== null && !in_array($type, [
FirewallRuleObject::TYPE_IP,
FirewallRuleObject::TYPE_IP_RANGE,
FirewallRuleObject::TYPE_DEVICE,
], true)) {
throw new \InvalidArgumentException('Invalid rule type filter.');
}
if ($action !== null && !in_array($action, [
FirewallRuleObject::ACTION_ALLOW,
FirewallRuleObject::ACTION_BLOCK,
], true)) {
throw new \InvalidArgumentException('Invalid rule action filter.');
}
if ($limit < 1 || $limit > self::MAX_QUERY_LIMIT || $offset < 0) {
throw new \InvalidArgumentException('Pagination requires limit 1-100 and offset 0 or greater.');
}
return $this->store->queryRules(
$scope->scope,
$scope->tenantId,
$status,
$type,
$action,
$limit,
$offset
);
}
public function fetch(FirewallRuleScope $scope, string $ruleId): ?FirewallRuleObject
{
return $this->ownedRule($scope, $ruleId);
}
/** @return array{precedence: string[], system: FirewallRuleObject[], tenant: FirewallRuleObject[]} */
public function effectivePolicy(string $tenantId): array
{
return [
'precedence' => ['system_block', 'tenant_allow', 'tenant_block', 'system_allow', 'default_allow'],
'system' => $this->store->listSystemRules(),
'tenant' => $this->store->listRules($tenantId),
];
}
public function createManualRule(
FirewallRuleScope $scope,
string $type,
string $action,
string $value,
string $reason,
?string $createdBy,
?int $durationSeconds = null,
?string $currentIp = null,
bool $confirmCurrentIp = false
): FirewallRuleObject {
$reason = trim($reason);
if ($reason === '' || strlen($reason) > 1000) {
throw new \InvalidArgumentException('A rule reason containing 1-1000 bytes is required.');
}
if ($currentIp !== null) {
$currentIp = FirewallRuleValidator::ipAddress($currentIp);
}
if (
!$confirmCurrentIp
&& $currentIp !== null
&& $action === FirewallRuleObject::ACTION_BLOCK
&& $this->matchesIp($type, $value, $currentIp)
) {
throw new FirewallRuleConflictException(
'current_ip_confirmation_required',
'This rule would block your current IP address. Explicit confirmation is required.'
);
}
return match ([$type, $action]) {
[FirewallRuleObject::TYPE_IP, FirewallRuleObject::ACTION_BLOCK] =>
$this->blockIp($scope, $value, $reason, $createdBy, $durationSeconds),
[FirewallRuleObject::TYPE_IP, FirewallRuleObject::ACTION_ALLOW] =>
$durationSeconds === null
? $this->allowIp($scope, $value, $reason, $createdBy)
: throw new \InvalidArgumentException('Temporary allow rules are not supported.'),
[FirewallRuleObject::TYPE_IP_RANGE, FirewallRuleObject::ACTION_BLOCK] =>
$durationSeconds === null
? $this->blockIpRange($scope, $value, $reason, $createdBy)
: throw new \InvalidArgumentException('Temporary CIDR rules are not supported.'),
[FirewallRuleObject::TYPE_DEVICE, FirewallRuleObject::ACTION_BLOCK] =>
$this->blockDevice($scope, $value, $reason, $createdBy, $durationSeconds),
default => throw new \InvalidArgumentException('Unsupported firewall rule type and action combination.'),
};
}
private function matchesIp(string $type, string $value, string $currentIp): bool
{
if ($type === FirewallRuleObject::TYPE_IP) {
$value = FirewallRuleValidator::ipAddress($value);
return inet_pton($value) === inet_pton($currentIp);
}
if ($type === FirewallRuleObject::TYPE_IP_RANGE) {
return IpUtils::checkIp($currentIp, FirewallRuleValidator::cidr($value));
}
return false;
}
public function blockIp(
FirewallRuleScope $scope,
string $ipAddress,
?string $reason,
?string $createdBy,
?int $durationSeconds = null,
string $origin = self::ORIGIN_MANUAL,
array $metadata = []
): FirewallRuleObject {
$ipAddress = FirewallRuleValidator::ipAddress($ipAddress);
FirewallRuleValidator::duration($durationSeconds);
$existing = $this->store->findExactIpRule(
$scope->tenantId,
$ipAddress,
FirewallRuleObject::ACTION_BLOCK,
$scope->scope
);
if ($existing) {
if (
$origin === self::ORIGIN_AUTOMATIC
&& ($existing->getMetadata()['origin'] ?? null) === self::ORIGIN_AUTOMATIC
&& $durationSeconds !== null
) {
return $this->extendAutomaticBlock($existing, $durationSeconds, $metadata);
}
return $existing;
}
$rule = $this->create(
$scope,
FirewallRuleObject::TYPE_IP,
FirewallRuleObject::ACTION_BLOCK,
$ipAddress,
$reason ?? 'Blocked by administrator',
$createdBy,
$durationSeconds,
$origin,
$metadata
);
$this->events->dispatch(new IpBlockedEvent($ipAddress, $reason, $scope->tenantId));
return $rule;
}
public function allowIp(
FirewallRuleScope $scope,
string $ipAddress,
?string $reason,
?string $createdBy,
string $origin = self::ORIGIN_MANUAL
): FirewallRuleObject {
$ipAddress = FirewallRuleValidator::ipAddress($ipAddress);
$rule = $this->create(
$scope,
FirewallRuleObject::TYPE_IP,
FirewallRuleObject::ACTION_ALLOW,
$ipAddress,
$reason ?? 'Allowed by administrator',
$createdBy,
null,
$origin
);
$this->events->dispatch(new IpAllowedEvent($ipAddress, $reason, $scope->tenantId));
return $rule;
}
public function blockIpRange(
FirewallRuleScope $scope,
string $cidr,
?string $reason,
?string $createdBy,
string $origin = self::ORIGIN_MANUAL
): FirewallRuleObject {
return $this->create(
$scope,
FirewallRuleObject::TYPE_IP_RANGE,
FirewallRuleObject::ACTION_BLOCK,
FirewallRuleValidator::cidr($cidr),
$reason ?? 'Range blocked by administrator',
$createdBy,
null,
$origin
);
}
public function blockDevice(
FirewallRuleScope $scope,
string $fingerprint,
?string $reason,
?string $createdBy,
?int $durationSeconds = null,
string $origin = self::ORIGIN_MANUAL
): FirewallRuleObject {
FirewallRuleValidator::duration($durationSeconds);
$fingerprint = FirewallRuleValidator::deviceFingerprint($fingerprint);
$rule = $this->create(
$scope,
FirewallRuleObject::TYPE_DEVICE,
FirewallRuleObject::ACTION_BLOCK,
$fingerprint,
$reason ?? 'Device blocked by administrator',
$createdBy,
$durationSeconds,
$origin
);
$event = new DeviceBlockedEvent($fingerprint, $reason, $scope->tenantId);
$this->events->dispatch($event);
return $rule;
}
public function disableManual(
FirewallRuleScope $scope,
string $ruleId,
string $reason,
?string $actorId
): ?FirewallRuleObject {
$reason = self::manualReason($reason);
$rule = $this->ownedRule($scope, $ruleId);
if (!$rule) {
return null;
}
if ($rule->isEnabled()) {
$rule->setEnabled(false);
$this->store->depositRule($rule);
$this->cache->invalidate();
$this->publishLifecycleEvent(
FirewallRuleDisabledEvent::class,
$rule,
$actorId,
['changeReason' => $reason, 'changeOrigin' => self::ORIGIN_MANUAL]
);
}
return $rule;
}
public function enableManual(
FirewallRuleScope $scope,
string $ruleId,
string $reason,
?string $actorId,
?string $currentIp = null,
bool $confirmCurrentIp = false
): ?FirewallRuleObject {
$reason = self::manualReason($reason);
$rule = $this->ownedRule($scope, $ruleId);
if (!$rule) {
return null;
}
if (
!$confirmCurrentIp
&& $currentIp !== null
&& $rule->getAction() === FirewallRuleObject::ACTION_BLOCK
&& $this->matchesIp($rule->getType(), (string)$rule->getValue(), FirewallRuleValidator::ipAddress($currentIp))
) {
throw new FirewallRuleConflictException(
'current_ip_confirmation_required',
'Enabling this rule would block your current IP address. Explicit confirmation is required.'
);
}
if (!$rule->isEnabled()) {
$rule->setEnabled(true);
$this->store->depositRule($rule);
$this->cache->invalidate();
$this->publishLifecycleEvent(
FirewallRuleEnabledEvent::class,
$rule,
$actorId,
['changeReason' => $reason, 'changeOrigin' => self::ORIGIN_MANUAL]
);
}
return $rule;
}
public function extendManual(
FirewallRuleScope $scope,
string $ruleId,
int $durationSeconds,
string $reason,
?string $actorId
): ?FirewallRuleObject {
$reason = self::manualReason($reason);
FirewallRuleValidator::duration($durationSeconds);
$rule = $this->ownedRule($scope, $ruleId);
if (!$rule) {
return null;
}
$previousExpiry = $rule->getExpiresAt();
if ($previousExpiry === null) {
throw new \InvalidArgumentException('Permanent firewall rules cannot be extended.');
}
$now = new \DateTimeImmutable();
$newExpiry = ($previousExpiry > $now ? $previousExpiry : $now)
->modify("+{$durationSeconds} seconds");
$metadata = $rule->getMetadata() ?? [];
$extensions = is_array($metadata['extensions'] ?? null) ? $metadata['extensions'] : [];
$extensions[] = [
'extendedAt' => $now->format(\DateTimeInterface::ATOM),
'previousExpiresAt' => $previousExpiry->format(\DateTimeInterface::ATOM),
'expiresAt' => $newExpiry->format(\DateTimeInterface::ATOM),
'origin' => self::ORIGIN_MANUAL,
'actorId' => $actorId,
'reason' => $reason,
];
$rule->setExpiresAt($newExpiry)->setMetadata([...$metadata, 'extensions' => $extensions]);
$this->store->depositRule($rule);
$this->cache->invalidate();
$this->publishLifecycleEvent(
FirewallRuleExtendedEvent::class,
$rule,
$actorId,
[
'changeReason' => $reason,
'changeOrigin' => self::ORIGIN_MANUAL,
'previousExpiresAt' => $previousExpiry->format(\DateTimeInterface::ATOM),
]
);
return $rule;
}
public function removeManual(
FirewallRuleScope $scope,
string $ruleId,
string $reason,
?string $actorId
): ?FirewallRuleObject {
$reason = self::manualReason($reason);
$rule = $this->ownedRule($scope, $ruleId);
if (!$rule) {
return null;
}
$this->store->destroyRule($rule);
$this->cache->invalidate();
$this->publishLifecycleEvent(
FirewallRuleRemovedEvent::class,
$rule,
$actorId,
['changeReason' => $reason, 'changeOrigin' => self::ORIGIN_MANUAL]
);
return $rule;
}
private static function manualReason(string $reason): string
{
$reason = trim($reason);
if ($reason === '' || strlen($reason) > 1000) {
throw new \InvalidArgumentException('A change reason containing 1-1000 bytes is required.');
}
return $reason;
}
private function create(
FirewallRuleScope $scope,
string $type,
string $action,
string $value,
string $reason,
?string $createdBy,
?int $durationSeconds = null,
string $origin = self::ORIGIN_MANUAL,
array $metadata = []
): FirewallRuleObject {
if (!in_array($origin, [self::ORIGIN_MANUAL, self::ORIGIN_AUTOMATIC], true)) {
throw new \InvalidArgumentException("Invalid firewall rule origin: {$origin}");
}
$rule = (new FirewallRuleObject())
->setScope($scope->scope)
->setTenantId($scope->tenantId)
->setType($type)
->setAction($action)
->setValue($value)
->setReason($reason)
->setCreatedBy($createdBy)
->setCreatedAt(new \DateTimeImmutable())
->setEnabled(true);
if ($durationSeconds !== null) {
$rule->setExpiresAt((new \DateTimeImmutable())->modify("+{$durationSeconds} seconds"));
}
$metadata = [...$metadata, 'origin' => $origin];
if ($origin === self::ORIGIN_AUTOMATIC && $rule->getExpiresAt() !== null) {
$metadata['originalExpiresAt'] = $rule->getExpiresAt()->format(\DateTimeInterface::ATOM);
$metadata['extensions'] = [];
}
$rule->setMetadata($metadata);
$rule = $this->store->depositRule($rule)
?? throw new \RuntimeException('Failed to persist firewall rule.');
$this->cache->invalidate();
$this->publishLifecycleEvent(FirewallRuleCreatedEvent::class, $rule);
return $rule;
}
private function extendAutomaticBlock(
FirewallRuleObject $rule,
int $durationSeconds,
array $policy
): FirewallRuleObject {
$now = new \DateTimeImmutable();
$previousExpiry = $rule->getExpiresAt();
$newExpiry = $now->modify("+{$durationSeconds} seconds");
if ($previousExpiry !== null && $newExpiry <= $previousExpiry) {
return $rule;
}
$metadata = $rule->getMetadata() ?? [];
$extensions = is_array($metadata['extensions'] ?? null) ? $metadata['extensions'] : [];
$extensions[] = [
'extendedAt' => $now->format(\DateTimeInterface::ATOM),
'previousExpiresAt' => $previousExpiry?->format(\DateTimeInterface::ATOM),
'expiresAt' => $newExpiry->format(\DateTimeInterface::ATOM),
'failureCount' => $policy['lastFailureCount'] ?? null,
];
$rule->setExpiresAt($newExpiry)->setMetadata([
...$metadata,
...$policy,
'origin' => self::ORIGIN_AUTOMATIC,
'originalExpiresAt' => $metadata['originalExpiresAt']
?? $previousExpiry?->format(\DateTimeInterface::ATOM),
'extensions' => $extensions,
'lastExtendedAt' => $now->format(\DateTimeInterface::ATOM),
]);
$this->store->depositRule($rule);
$this->cache->invalidate();
$this->publishLifecycleEvent(FirewallRuleExtendedEvent::class, $rule);
return $rule;
}
private function ownedRule(FirewallRuleScope $scope, string $ruleId): ?FirewallRuleObject
{
$rule = $this->store->fetchRule($ruleId);
return $rule && $scope->owns($rule) ? $rule : null;
}
/**
* @param class-string<FirewallRuleEvent> $eventClass
*/
private function publishLifecycleEvent(
string $eventClass,
FirewallRuleObject $rule,
?string $actorId = null,
array $change = []
): void
{
$event = $eventClass::fromRule($rule, $actorId, $change);
$this->events->dispatch($event);
}
}
+35
View File
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace KTXC\Service;
use KTXC\Models\Firewall\FirewallRuleObject;
final class FirewallRuleScope
{
private function __construct(
public readonly string $scope,
public readonly ?string $tenantId,
) {
}
public static function tenant(string $tenantId): self
{
if ($tenantId === '') {
throw new \InvalidArgumentException('Tenant firewall rule scope requires a tenant ID.');
}
return new self(FirewallRuleObject::SCOPE_TENANT, $tenantId);
}
public static function system(): self
{
return new self(FirewallRuleObject::SCOPE_SYSTEM, null);
}
public function owns(FirewallRuleObject $rule): bool
{
return $rule->getScope() === $this->scope && $rule->getTenantId() === $this->tenantId;
}
}
@@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
namespace KTXC\Service;
final class FirewallRuleValidator
{
public const MAX_DEVICE_FINGERPRINT_LENGTH = 512;
private function __construct()
{
}
public static function ipAddress(string $ipAddress): string
{
$ipAddress = trim($ipAddress);
if (filter_var($ipAddress, \FILTER_VALIDATE_IP) === false) {
throw new \InvalidArgumentException("Invalid IP address: {$ipAddress}");
}
return $ipAddress;
}
public static function cidr(string $cidr): string
{
$cidr = trim($cidr);
if (substr_count($cidr, '/') !== 1) {
throw new \InvalidArgumentException("Invalid CIDR range: {$cidr}");
}
[$address, $prefix] = explode('/', $cidr, 2);
if (filter_var($address, \FILTER_VALIDATE_IP) === false || !ctype_digit($prefix)) {
throw new \InvalidArgumentException("Invalid CIDR range: {$cidr}");
}
$maximumPrefix = str_contains($address, ':') ? 128 : 32;
if ((int)$prefix > $maximumPrefix) {
throw new \InvalidArgumentException("Invalid CIDR range: {$cidr}");
}
return $cidr;
}
public static function deviceFingerprint(string $fingerprint): string
{
$fingerprint = trim($fingerprint);
if ($fingerprint === '' || strlen($fingerprint) > self::MAX_DEVICE_FINGERPRINT_LENGTH) {
throw new \InvalidArgumentException(
sprintf('Device fingerprint must contain between 1 and %d bytes.', self::MAX_DEVICE_FINGERPRINT_LENGTH)
);
}
return $fingerprint;
}
public static function duration(?int $durationSeconds): void
{
if ($durationSeconds !== null && $durationSeconds < 1) {
throw new \InvalidArgumentException('Firewall rule duration must be greater than zero.');
}
}
}
+201 -364
View File
@@ -5,12 +5,26 @@ declare(strict_types=1);
namespace KTXC\Service;
use KTXC\Http\Request\Request;
use KTXC\Http\Request\RequestContext;
use KTXC\Models\Firewall\FirewallRuleObject;
use KTXC\Models\Firewall\FirewallLogObject;
use KTXC\Stores\FirewallStore;
use KTXC\Context\TenantContextInterface;
use KTXC\Security\Event\AccessDeniedEvent;
use KTXC\Security\Event\AuthenticationFailedEvent;
use KTXC\Security\Event\AuthenticationSucceededEvent;
use KTXC\Security\Event\BruteForceDetectedEvent;
use KTXC\Security\Event\FirewallRuleCreatedEvent;
use KTXC\Security\Event\FirewallRuleDisabledEvent;
use KTXC\Security\Event\FirewallRuleEnabledEvent;
use KTXC\Security\Event\FirewallRuleExtendedEvent;
use KTXC\Security\Event\FirewallRuleRemovedEvent;
use KTXC\Security\Event\FirewallSettingsUpdatedEvent;
use KTXC\Security\Event\RateLimitExceededEvent;
use KTXC\Security\Event\SuspiciousActivityEvent;
use KTXC\Security\Event\SecurityEventInterface;
use KTXC\Security\Event\SecurityRequestEventInterface;
use KTXF\Event\EventDispatcherInterface;
use KTXF\Event\SecurityEvent;
use KTXF\IpUtils;
/**
@@ -29,6 +43,9 @@ class FirewallService
private const DEFAULT_MAX_AUTH_FAILURES = 5;
private const DEFAULT_AUTH_FAILURE_WINDOW = 300; // 5 minutes
private const DEFAULT_AUTO_BLOCK_DURATION = 3600; // 1 hour
private const MAX_AUTH_FAILURES = 1000;
private const MAX_AUTH_FAILURE_WINDOW = 86400; // 1 day
private const MAX_AUTO_BLOCK_DURATION = 31536000; // 1 year
// Configuration keys
private const CONFIG_MAX_FAILURES = 'firewall.maxAuthFailures';
@@ -36,13 +53,13 @@ class FirewallService
private const CONFIG_AUTO_BLOCK_DURATION = 'firewall.autoBlockDuration';
private const CONFIG_ENABLED = 'firewall.enabled';
/** @var FirewallRuleObject[]|null */
private ?array $rulesCache = null;
public function __construct(
private readonly FirewallStore $store,
private readonly TenantContextInterface $tenantContext,
private readonly EventDispatcherInterface $events,
private readonly FirewallRuleManager $rules,
private readonly FirewallRuleCache $ruleCache,
private readonly RequestContext $requestContext,
) {
}
@@ -71,36 +88,33 @@ class FirewallService
string $ipAddress,
?string $deviceFingerprint = null
): FirewallAnalyzeResult {
// Check if firewall is enabled for this tenant
if (!$this->isEnabled()) {
return new FirewallAnalyzeResult(true);
}
$tenantId = $this->tenantContext->identifier();
if (!$tenantId) {
return new FirewallAnalyzeResult(true);
$ruleGroups = [
[$this->ruleCache->system(), FirewallRuleObject::ACTION_BLOCK],
];
if ($tenantId !== null && $this->isEnabled()) {
$tenantRules = $this->ruleCache->tenant($tenantId);
$ruleGroups[] = [$tenantRules, FirewallRuleObject::ACTION_ALLOW];
$ruleGroups[] = [$tenantRules, FirewallRuleObject::ACTION_BLOCK];
}
$rules = $this->getActiveRules();
$ruleGroups[] = [$this->ruleCache->system(), FirewallRuleObject::ACTION_ALLOW];
// First check for explicit allow rules (whitelist takes precedence)
foreach ($rules as $rule) {
if ($rule->getAction() !== FirewallRuleObject::ACTION_ALLOW) {
continue;
}
if ($this->ruleMatchesRequest($rule, $ipAddress, $deviceFingerprint)) {
return new FirewallAnalyzeResult(true, $rule->getId(), 'Explicitly allowed');
}
}
foreach ($ruleGroups as [$rules, $action]) {
foreach ($rules as $rule) {
if ($rule->getAction() !== $action) {
continue;
}
if (!$this->ruleMatchesRequest($rule, $ipAddress, $deviceFingerprint)) {
continue;
}
if ($action === FirewallRuleObject::ACTION_ALLOW) {
return new FirewallAnalyzeResult(true, $rule->getId(), 'Explicitly allowed');
}
// Then check for block rules
foreach ($rules as $rule) {
if ($rule->getAction() !== FirewallRuleObject::ACTION_BLOCK) {
continue;
}
if ($this->ruleMatchesRequest($rule, $ipAddress, $deviceFingerprint)) {
$this->publishAccessDenied($ipAddress, $deviceFingerprint, $rule);
return new FirewallAnalyzeResult(false, $rule->getId(), $rule->getReason());
}
@@ -131,23 +145,31 @@ class FirewallService
/**
* Handle authentication failure event
*/
public function handleAuthFailure(SecurityEvent $event): void
public function handleAuthFailure(AuthenticationFailedEvent $event): void
{
$ipAddress = $event->getIpAddress();
$tenantId = $event->getTenantId() ?? $this->tenantContext->identifier();
$request = $this->requestContext->current();
$ipAddress = $request?->getClientIp();
$tenantId = $event->tenantIdentifier() ?? $this->tenantContext->identifier();
if (!$ipAddress || !$tenantId) {
return;
}
$log = $this->securityLog($event, $request);
if ($log === null || !$this->store->createLogOnce($log)) {
return;
}
// Check for brute force
$windowSeconds = $this->getConfig(
$windowSeconds = $this->getBoundedIntegerConfig(
self::CONFIG_FAILURE_WINDOW,
self::DEFAULT_AUTH_FAILURE_WINDOW
self::DEFAULT_AUTH_FAILURE_WINDOW,
self::MAX_AUTH_FAILURE_WINDOW
);
$maxFailures = $this->getConfig(
$maxFailures = $this->getBoundedIntegerConfig(
self::CONFIG_MAX_FAILURES,
self::DEFAULT_MAX_AUTH_FAILURES
self::DEFAULT_MAX_AUTH_FAILURES,
self::MAX_AUTH_FAILURES
);
$failureCount = $this->store->countRecentFailures(
@@ -156,11 +178,24 @@ class FirewallService
$windowSeconds
);
// Include current failure in count
$failureCount++;
if ($failureCount >= $maxFailures) {
$this->handleBruteForce($ipAddress, $failureCount, $windowSeconds);
$blockDuration = $this->getBoundedIntegerConfig(
self::CONFIG_AUTO_BLOCK_DURATION,
self::DEFAULT_AUTO_BLOCK_DURATION,
self::MAX_AUTO_BLOCK_DURATION
);
$responseCooldown = min($windowSeconds, max(1, intdiv($blockDuration, 2)));
if (!$this->store->claimBruteForce($tenantId, $ipAddress, $responseCooldown)) {
return;
}
$this->handleBruteForce(
$tenantId,
$ipAddress,
$failureCount,
$windowSeconds,
$blockDuration
);
}
}
@@ -168,53 +203,91 @@ class FirewallService
* Handle detected brute force attack
*/
private function handleBruteForce(
string $tenantId,
string $ipAddress,
int $failureCount,
int $windowSeconds
int $windowSeconds,
int $blockDuration
): void {
// Publish brute force event
$event = SecurityEvent::bruteForceDetected($ipAddress, $failureCount, $windowSeconds);
$event->setTenantId($this->tenantContext->identifier());
$event = new BruteForceDetectedEvent(
$ipAddress,
$failureCount,
$windowSeconds,
$tenantId,
);
$this->events->dispatch($event);
// Auto-block the IP
$blockDuration = $this->getConfig(
self::CONFIG_AUTO_BLOCK_DURATION,
self::DEFAULT_AUTO_BLOCK_DURATION
);
$this->blockIp(
$this->rules->blockIp(
FirewallRuleScope::tenant($tenantId),
$ipAddress,
sprintf('Auto-blocked: %d failed auth attempts in %d seconds', $failureCount, $windowSeconds),
null, // System-created
$blockDuration
$blockDuration,
FirewallRuleManager::ORIGIN_AUTOMATIC,
[
'failureThreshold' => $this->getBoundedIntegerConfig(
self::CONFIG_MAX_FAILURES,
self::DEFAULT_MAX_AUTH_FAILURES,
self::MAX_AUTH_FAILURES
),
'failureWindowSeconds' => $windowSeconds,
'lastFailureCount' => $failureCount,
'blockDurationSeconds' => $blockDuration,
]
);
}
/**
* Log security event to firewall logs
*/
public function logSecurityEvent(SecurityEvent $event): void
public function logSecurityEvent(SecurityEventInterface $event): void
{
$tenantId = $event->getTenantId() ?? $this->tenantContext->identifier();
if (!$tenantId) {
return;
$log = $this->securityLog($event);
if ($log !== null) {
$this->store->createLog($log);
}
}
public function logAuthenticationSuccess(AuthenticationSucceededEvent $event): void
{
$log = $this->securityLog($event, $this->requestContext->current());
if ($log !== null) {
$this->store->createLog($log);
}
}
private function securityLog(
SecurityEventInterface $event,
?Request $request = null,
): ?FirewallLogObject
{
$tenantId = $event->tenantIdentifier() ?? $this->tenantContext->identifier();
$ruleScope = $event->get('ruleScope');
if (!$tenantId && $ruleScope !== FirewallRuleObject::SCOPE_SYSTEM) {
return null;
}
$log = new FirewallLogObject();
$log->setTenantId($tenantId)
->setIpAddress($event->getIpAddress())
->setDeviceFingerprint($event->getDeviceFingerprint())
->setUserAgent($event->getUserAgent())
->setRequestPath($event->getRequestPath())
->setRequestMethod($event->getRequestMethod())
->setEventType($this->mapEventToLogType($event->getName()))
->setResult($this->mapEventToResult($event->getName()))
->setIdentityId($event->getUserId())
->setTimestamp(new \DateTimeImmutable())
->setMetadata($event->getData());
$requestEvent = $event instanceof SecurityRequestEventInterface ? $event : null;
$this->store->createLog($log);
$log = new FirewallLogObject();
return $log->setEventId($event->identifier())
->setTenantId($tenantId)
->setIpAddress($request?->getClientIp() ?? $requestEvent?->getIpAddress())
->setDeviceFingerprint(
$request?->headers->get('X-Device-Fingerprint')
?? $requestEvent?->getDeviceFingerprint()
)
->setUserAgent($request?->headers->get('User-Agent') ?? $requestEvent?->getUserAgent())
->setRequestPath($request?->getPathInfo() ?? $requestEvent?->getRequestPath())
->setRequestMethod($request?->getMethod() ?? $requestEvent?->getRequestMethod())
->setEventType($this->mapEventToLogType($event->label()))
->setResult($this->mapEventToResult($event))
->setRuleId($event->get('ruleId'))
->setRuleScope($ruleScope)
->setIdentityId($event->getUserId() ?? $event->actorIdentity())
->setTimestamp(new \DateTimeImmutable())
->setMetadata($event->context());
}
/**
@@ -223,12 +296,18 @@ class FirewallService
private function mapEventToLogType(string $eventName): string
{
return match ($eventName) {
SecurityEvent::AUTH_FAILURE => FirewallLogObject::EVENT_AUTH_FAILURE,
SecurityEvent::AUTH_SUCCESS => FirewallLogObject::EVENT_ACCESS_CHECK,
SecurityEvent::BRUTE_FORCE_DETECTED => FirewallLogObject::EVENT_BRUTE_FORCE,
SecurityEvent::RATE_LIMIT_EXCEEDED => FirewallLogObject::EVENT_RATE_LIMIT,
SecurityEvent::ACCESS_DENIED => FirewallLogObject::EVENT_RULE_MATCH,
SecurityEvent::SUSPICIOUS_ACTIVITY => FirewallLogObject::EVENT_SUSPICIOUS,
AuthenticationFailedEvent::class => FirewallLogObject::EVENT_AUTH_FAILURE,
AuthenticationSucceededEvent::class => FirewallLogObject::EVENT_ACCESS_CHECK,
BruteForceDetectedEvent::class => FirewallLogObject::EVENT_BRUTE_FORCE,
RateLimitExceededEvent::class => FirewallLogObject::EVENT_RATE_LIMIT,
AccessDeniedEvent::class => FirewallLogObject::EVENT_RULE_MATCH,
SuspiciousActivityEvent::class => FirewallLogObject::EVENT_SUSPICIOUS,
FirewallRuleCreatedEvent::class => FirewallLogObject::EVENT_RULE_CREATED,
FirewallRuleExtendedEvent::class => FirewallLogObject::EVENT_RULE_EXTENDED,
FirewallRuleEnabledEvent::class => FirewallLogObject::EVENT_RULE_ENABLED,
FirewallRuleDisabledEvent::class => FirewallLogObject::EVENT_RULE_DISABLED,
FirewallRuleRemovedEvent::class => FirewallLogObject::EVENT_RULE_REMOVED,
FirewallSettingsUpdatedEvent::class => FirewallLogObject::EVENT_SETTINGS_UPDATED,
default => FirewallLogObject::EVENT_ACCESS_CHECK,
};
}
@@ -236,11 +315,16 @@ class FirewallService
/**
* Map security event to result
*/
private function mapEventToResult(string $eventName): string
private function mapEventToResult(SecurityEventInterface $event): string
{
return match ($eventName) {
SecurityEvent::AUTH_SUCCESS,
SecurityEvent::ACCESS_GRANTED => FirewallLogObject::RESULT_ALLOWED,
return match ($event->label()) {
AuthenticationSucceededEvent::class => FirewallLogObject::RESULT_ALLOWED,
FirewallRuleCreatedEvent::class,
FirewallRuleExtendedEvent::class,
FirewallRuleEnabledEvent::class,
FirewallRuleDisabledEvent::class,
FirewallRuleRemovedEvent::class,
FirewallSettingsUpdatedEvent::class => FirewallLogObject::RESULT_RECORDED,
default => FirewallLogObject::RESULT_BLOCKED,
};
}
@@ -253,272 +337,17 @@ class FirewallService
?string $deviceFingerprint,
FirewallRuleObject $rule
): void {
$event = SecurityEvent::accessDenied(
$ipAddress,
$deviceFingerprint,
$rule->getId(),
$rule->getReason()
$event = new AccessDeniedEvent(
ipAddress: $ipAddress,
ruleId: $rule->getId(),
ruleScope: $rule->getScope(),
deviceFingerprint: $deviceFingerprint,
reason: $rule->getReason(),
tenantId: $this->tenantContext->identifier(),
);
$event->setTenantId($this->tenantContext->identifier());
$this->events->dispatch($event);
}
// ========================================
// Rule Management
// ========================================
/**
* Block an IP address
*/
public function blockIp(
string $ipAddress,
?string $reason = null,
?string $createdBy = null,
?int $durationSeconds = null
): FirewallRuleObject {
$tenantId = $this->tenantContext->identifier();
if (!$tenantId) {
throw new \RuntimeException('Cannot create firewall rule: no tenant configured');
}
// Check if already blocked
$existing = $this->store->findExactIpRule(
$tenantId,
$ipAddress,
FirewallRuleObject::ACTION_BLOCK
);
if ($existing) {
return $existing;
}
$rule = new FirewallRuleObject();
$rule->setTenantId($tenantId)
->setType(FirewallRuleObject::TYPE_IP)
->setAction(FirewallRuleObject::ACTION_BLOCK)
->setValue($ipAddress)
->setReason($reason ?? 'Blocked by administrator')
->setCreatedBy($createdBy)
->setCreatedAt(new \DateTimeImmutable())
->setEnabled(true);
if ($durationSeconds !== null) {
$rule->setExpiresAt(
(new \DateTimeImmutable())->modify("+{$durationSeconds} seconds")
);
}
$this->store->depositRule($rule);
$this->clearRulesCache();
// Publish event
$event = new SecurityEvent(SecurityEvent::IP_BLOCKED, ['ip' => $ipAddress, 'reason' => $reason]);
$event->setIpAddress($ipAddress)
->setReason($reason)
->setTenantId($tenantId);
$this->events->dispatch($event);
return $rule;
}
/**
* Allow an IP address (whitelist)
*/
public function allowIp(
string $ipAddress,
?string $reason = null,
?string $createdBy = null
): FirewallRuleObject {
$tenantId = $this->tenantContext->identifier();
if (!$tenantId) {
throw new \RuntimeException('Cannot create firewall rule: no tenant configured');
}
$rule = new FirewallRuleObject();
$rule->setTenantId($tenantId)
->setType(FirewallRuleObject::TYPE_IP)
->setAction(FirewallRuleObject::ACTION_ALLOW)
->setValue($ipAddress)
->setReason($reason ?? 'Allowed by administrator')
->setCreatedBy($createdBy)
->setCreatedAt(new \DateTimeImmutable())
->setEnabled(true);
$this->store->depositRule($rule);
$this->clearRulesCache();
// Publish event
$event = new SecurityEvent(SecurityEvent::IP_ALLOWED, ['ip' => $ipAddress, 'reason' => $reason]);
$event->setIpAddress($ipAddress)
->setReason($reason)
->setTenantId($tenantId);
$this->events->dispatch($event);
return $rule;
}
/**
* Block an IP range (CIDR notation)
*/
public function blockIpRange(
string $cidr,
?string $reason = null,
?string $createdBy = null
): FirewallRuleObject {
$tenantId = $this->tenantContext->identifier();
if (!$tenantId) {
throw new \RuntimeException('Cannot create firewall rule: no tenant configured');
}
$rule = new FirewallRuleObject();
$rule->setTenantId($tenantId)
->setType(FirewallRuleObject::TYPE_IP_RANGE)
->setAction(FirewallRuleObject::ACTION_BLOCK)
->setValue($cidr)
->setReason($reason ?? 'Range blocked by administrator')
->setCreatedBy($createdBy)
->setCreatedAt(new \DateTimeImmutable())
->setEnabled(true);
$this->store->depositRule($rule);
$this->clearRulesCache();
return $rule;
}
/**
* Block a device fingerprint
*/
public function blockDevice(
string $fingerprint,
?string $reason = null,
?string $createdBy = null,
?int $durationSeconds = null
): FirewallRuleObject {
$tenantId = $this->tenantContext->identifier();
if (!$tenantId) {
throw new \RuntimeException('Cannot create firewall rule: no tenant configured');
}
$rule = new FirewallRuleObject();
$rule->setTenantId($tenantId)
->setType(FirewallRuleObject::TYPE_DEVICE)
->setAction(FirewallRuleObject::ACTION_BLOCK)
->setValue($fingerprint)
->setReason($reason ?? 'Device blocked by administrator')
->setCreatedBy($createdBy)
->setCreatedAt(new \DateTimeImmutable())
->setEnabled(true);
if ($durationSeconds !== null) {
$rule->setExpiresAt(
(new \DateTimeImmutable())->modify("+{$durationSeconds} seconds")
);
}
$this->store->depositRule($rule);
$this->clearRulesCache();
// Publish event
$event = new SecurityEvent(SecurityEvent::DEVICE_BLOCKED, ['device' => $fingerprint, 'reason' => $reason]);
$event->setDeviceFingerprint($fingerprint)
->setReason($reason)
->setTenantId($tenantId);
$this->events->dispatch($event);
return $rule;
}
/**
* Remove a rule by ID
*/
public function removeRule(string $ruleId): bool
{
$rule = $this->store->fetchRule($ruleId);
if (!$rule) {
return false;
}
// Verify tenant ownership
if ($rule->getTenantId() !== $this->tenantContext->identifier()) {
return false;
}
$this->store->destroyRule($rule);
$this->clearRulesCache();
return true;
}
/**
* Disable a rule (soft delete)
*/
public function disableRule(string $ruleId): bool
{
$rule = $this->store->fetchRule($ruleId);
if (!$rule) {
return false;
}
// Verify tenant ownership
if ($rule->getTenantId() !== $this->tenantContext->identifier()) {
return false;
}
$rule->setEnabled(false);
$this->store->depositRule($rule);
$this->clearRulesCache();
return true;
}
/**
* Get all rules for current tenant
*/
public function listRules(bool $activeOnly = true): array
{
$tenantId = $this->tenantContext->identifier();
if (!$tenantId) {
return [];
}
return $this->store->listRules($tenantId, $activeOnly);
}
/**
* Get firewall logs for current tenant
*/
public function getLogs(
?string $ipAddress = null,
?string $eventType = null,
?string $result = null,
int $limit = 100
): array {
$tenantId = $this->tenantContext->identifier();
if (!$tenantId) {
return [];
}
return $this->store->listLogs($tenantId, $ipAddress, $eventType, $result, $limit);
}
/**
* Get blocked requests count
*/
public function getBlockedCount(?\DateTimeImmutable $since = null): int
{
$tenantId = $this->tenantContext->identifier();
if (!$tenantId) {
return 0;
}
return $this->store->countBlockedRequests($tenantId, $since);
}
// ========================================
// Helpers
// ========================================
/**
* Check if firewall is enabled for current tenant
*/
@@ -533,6 +362,9 @@ class FirewallService
private function getConfig(string $key, mixed $default = null): mixed
{
$config = $this->tenantContext->configuration();
if ($config instanceof \JsonSerializable) {
$config = $config->jsonSerialize();
}
$parts = explode('.', $key);
foreach ($parts as $part) {
@@ -545,27 +377,14 @@ class FirewallService
return $config;
}
/**
* Get active rules (cached)
* @return FirewallRuleObject[]
*/
private function getActiveRules(): array
private function getBoundedIntegerConfig(string $key, int $default, int $maximum): int
{
if ($this->rulesCache === null) {
$tenantId = $this->tenantContext->identifier();
$this->rulesCache = $tenantId
? $this->store->listRules($tenantId, true)
: [];
$value = $this->getConfig($key, $default);
if (!is_int($value) || $value < 1 || $value > $maximum) {
return $default;
}
return $this->rulesCache;
}
/**
* Clear rules cache
*/
private function clearRulesCache(): void
{
$this->rulesCache = null;
return $value;
}
/**
@@ -573,13 +392,31 @@ class FirewallService
*/
public function cleanup(): array
{
$expiredRules = $this->store->cleanupExpiredRules();
$oldLogs = $this->store->cleanupOldLogs(30);
$startedAt = new \DateTimeImmutable();
return [
'expiredRules' => $expiredRules,
'oldLogs' => $oldLogs,
];
try {
$result = [
'expiredRules' => $this->store->cleanupExpiredRules(),
'oldLogs' => $this->store->cleanupOldLogs(30),
'expiredBruteForceClaims' => $this->store->cleanupExpiredBruteForceClaims(),
];
$this->store->recordMaintenanceStatus($startedAt, new \DateTimeImmutable(), 'success', $result);
return $result;
} catch (\Throwable $error) {
try {
$this->store->recordMaintenanceStatus(
$startedAt,
new \DateTimeImmutable(),
'failed',
[],
$error->getMessage()
);
} catch (\Throwable) {
// Preserve the cleanup failure when the status store is also unavailable.
}
throw $error;
}
}
}
@@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
namespace KTXC\Service;
use KTXC\Models\Tenant\TenantConfiguration;
use KTXF\Event\EventDispatcherInterface;
use KTXC\Security\Event\FirewallSettingsUpdatedEvent;
final class FirewallSettingsService
{
public function __construct(
private readonly TenantService $tenants,
private readonly EventDispatcherInterface $events,
) {
}
public function update(
string $tenantId,
bool $enabled,
int $maxAuthFailures,
int $authFailureWindow,
int $autoBlockDuration,
string $reason,
?string $actorId
): ?array {
$reason = trim($reason);
if ($reason === '' || strlen($reason) > 1000) {
throw new \InvalidArgumentException('A change reason containing 1-1000 bytes is required.');
}
self::bounded($maxAuthFailures, 1, 1000, 'Maximum authentication failures');
self::bounded($authFailureWindow, 1, 86400, 'Authentication failure window');
self::bounded($autoBlockDuration, 1, 31536000, 'Automatic block duration');
$tenant = $this->tenants->fetchById($tenantId);
if ($tenant === null) {
return null;
}
$previous = $tenant->getConfiguration()->firewall()->jsonSerialize();
$current = [
'enabled' => $enabled,
'maxAuthFailures' => $maxAuthFailures,
'authFailureWindow' => $authFailureWindow,
'autoBlockDuration' => $autoBlockDuration,
];
$configuration = (new TenantConfiguration())->jsonDeserialize([
...$tenant->getConfiguration()->jsonSerialize(),
'firewall' => $current,
]);
$tenant->setConfiguration($configuration);
$this->tenants->deposit($tenant);
$event = new FirewallSettingsUpdatedEvent(
changeReason: $reason,
previous: $previous,
current: $current,
tenantId: $tenantId,
actorId: $actorId,
changeOrigin: FirewallRuleManager::ORIGIN_MANUAL,
);
$this->events->dispatch($event);
return $current;
}
private static function bounded(int $value, int $minimum, int $maximum, string $label): void
{
if ($value < $minimum || $value > $maximum) {
throw new \InvalidArgumentException(
"{$label} must be between {$minimum} and {$maximum}."
);
}
}
}
@@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
namespace KTXC\Service;
use KTXC\Stores\FirewallStore;
final class FirewallStatusService
{
public function __construct(private readonly FirewallStore $store)
{
}
public function tenantMetrics(string $tenantId, ?string $since = null): array
{
$sinceDate = self::date($since);
return [
'tenantId' => $tenantId,
'blockedRequests' => $this->store->countBlockedRequests($tenantId, $sinceDate),
'since' => $sinceDate?->format(\DateTimeInterface::ATOM),
];
}
public function systemMetrics(?string $tenantId = null, ?string $since = null): array
{
if ($tenantId !== null && ($tenantId === '' || strlen($tenantId) > 128)) {
throw new \InvalidArgumentException('Invalid tenant filter.');
}
$sinceDate = self::date($since);
return [
'tenantId' => $tenantId,
'blockedRequests' => $this->store->countSystemBlockedRequests($tenantId, $sinceDate),
'since' => $sinceDate?->format(\DateTimeInterface::ATOM),
];
}
public function maintenanceStatus(): array
{
return $this->store->maintenanceStatus() ?? [
'status' => 'never_run',
'startedAt' => null,
'completedAt' => null,
'result' => null,
'error' => null,
];
}
private static function date(?string $value): ?\DateTimeImmutable
{
if ($value === null) {
return null;
}
if ($value === '' || strlen($value) > 255) {
throw new \InvalidArgumentException('Invalid since date filter.');
}
try {
return new \DateTimeImmutable($value);
} catch (\Exception) {
throw new \InvalidArgumentException('Invalid since date filter.');
}
}
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace KTXC\Service;
use KTXC\Context\IdentityContextInterface;
final class SystemFirewallLogService
{
public const PERMISSION_READ = 'firewall.system.logs.read';
public function __construct(
private readonly FirewallLogService $logs,
private readonly IdentityContextInterface $identity,
) {
}
public function query(?string $tenantId, array $filters, int $limit = 50, int $offset = 0): array
{
if (!$this->identity->hasPermission(self::PERMISSION_READ)) {
throw new \RuntimeException('Missing required permission: '.self::PERMISSION_READ);
}
return $this->logs->system($tenantId, $filters, $limit, $offset);
}
}
@@ -0,0 +1,153 @@
<?php
declare(strict_types=1);
namespace KTXC\Service;
use KTXC\Context\IdentityContextInterface;
use KTXC\Models\Firewall\FirewallRuleObject;
final class SystemFirewallRuleService
{
public const PERMISSION_READ = 'firewall.system.rules.read';
public const PERMISSION_MANAGE = 'firewall.system.rules.manage';
public function __construct(
private readonly FirewallRuleManager $rules,
private readonly IdentityContextInterface $identity,
) {
}
public function listRules(bool $activeOnly = true): array
{
$this->requirePermission(self::PERMISSION_READ);
return $this->rules->list(FirewallRuleScope::system(), $activeOnly);
}
public function queryRules(
string $status = 'active',
?string $type = null,
?string $action = null,
int $limit = 50,
int $offset = 0
): array {
$this->requirePermission(self::PERMISSION_READ);
return $this->rules->query(FirewallRuleScope::system(), $status, $type, $action, $limit, $offset);
}
public function fetchRule(string $ruleId): ?FirewallRuleObject
{
$this->requirePermission(self::PERMISSION_READ);
return $this->rules->fetch(FirewallRuleScope::system(), $ruleId);
}
public function createRule(
string $type,
string $action,
string $value,
string $reason,
?int $durationSeconds = null,
?string $currentIp = null,
bool $confirmCurrentIp = false
): FirewallRuleObject {
$this->requirePermission(self::PERMISSION_MANAGE);
return $this->rules->createManualRule(
FirewallRuleScope::system(),
$type,
$action,
$value,
$reason,
$this->identity->identifier(),
$durationSeconds,
$currentIp,
$confirmCurrentIp
);
}
public function blockIp(string $ip, ?string $reason = null, ?int $durationSeconds = null): FirewallRuleObject
{
$this->requirePermission(self::PERMISSION_MANAGE);
return $this->rules->blockIp(
FirewallRuleScope::system(), $ip, $reason, $this->identity->identifier(), $durationSeconds
);
}
public function allowIp(string $ip, ?string $reason = null): FirewallRuleObject
{
$this->requirePermission(self::PERMISSION_MANAGE);
return $this->rules->allowIp(
FirewallRuleScope::system(), $ip, $reason, $this->identity->identifier()
);
}
public function blockIpRange(string $cidr, ?string $reason = null): FirewallRuleObject
{
$this->requirePermission(self::PERMISSION_MANAGE);
return $this->rules->blockIpRange(
FirewallRuleScope::system(), $cidr, $reason, $this->identity->identifier()
);
}
public function blockDevice(
string $fingerprint,
?string $reason = null,
?int $durationSeconds = null
): FirewallRuleObject {
$this->requirePermission(self::PERMISSION_MANAGE);
return $this->rules->blockDevice(
FirewallRuleScope::system(),
$fingerprint,
$reason,
$this->identity->identifier(),
$durationSeconds
);
}
public function disableRule(string $ruleId, string $reason): ?FirewallRuleObject
{
$this->requirePermission(self::PERMISSION_MANAGE);
return $this->rules->disableManual(
FirewallRuleScope::system(), $ruleId, $reason, $this->identity->identifier()
);
}
public function enableRule(
string $ruleId,
string $reason,
?string $currentIp = null,
bool $confirmCurrentIp = false
): ?FirewallRuleObject {
$this->requirePermission(self::PERMISSION_MANAGE);
return $this->rules->enableManual(
FirewallRuleScope::system(),
$ruleId,
$reason,
$this->identity->identifier(),
$currentIp,
$confirmCurrentIp
);
}
public function extendRule(string $ruleId, int $durationSeconds, string $reason): ?FirewallRuleObject
{
$this->requirePermission(self::PERMISSION_MANAGE);
return $this->rules->extendManual(
FirewallRuleScope::system(), $ruleId, $durationSeconds, $reason, $this->identity->identifier()
);
}
public function removeRule(string $ruleId, string $reason): ?FirewallRuleObject
{
$this->requirePermission(self::PERMISSION_MANAGE);
return $this->rules->removeManual(
FirewallRuleScope::system(), $ruleId, $reason, $this->identity->identifier()
);
}
private function requirePermission(string $permission): void
{
if (!$this->identity->hasPermission($permission)) {
throw new \RuntimeException("Missing required permission: {$permission}");
}
}
}
@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace KTXC\Service;
use KTXC\Context\IdentityContextInterface;
final class SystemFirewallStatusService
{
public const PERMISSION_MAINTENANCE_READ = 'firewall.system.maintenance.read';
public const PERMISSION_SETTINGS_MANAGE = 'firewall.system.settings.manage';
public function __construct(
private readonly FirewallStatusService $status,
private readonly IdentityContextInterface $identity,
private readonly FirewallSettingsService $settings,
) {
}
public function metrics(?string $tenantId = null, ?string $since = null): array
{
$this->requirePermission(SystemFirewallLogService::PERMISSION_READ);
return $this->status->systemMetrics($tenantId, $since);
}
public function maintenanceStatus(): array
{
$this->requirePermission(self::PERMISSION_MAINTENANCE_READ);
return $this->status->maintenanceStatus();
}
public function updateTenantConfiguration(
string $tenantId,
bool $enabled,
int $maxAuthFailures,
int $authFailureWindow,
int $autoBlockDuration,
string $reason
): ?array {
$this->requirePermission(self::PERMISSION_SETTINGS_MANAGE);
return $this->settings->update(
$tenantId,
$enabled,
$maxAuthFailures,
$authFailureWindow,
$autoBlockDuration,
$reason,
$this->identity->identifier()
);
}
private function requirePermission(string $permission): void
{
if (!$this->identity->hasPermission($permission)) {
throw new \RuntimeException("Missing required permission: {$permission}");
}
}
}
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace KTXC\Service;
use KTXC\Context\IdentityContextInterface;
use KTXC\Context\TenantContextInterface;
final class TenantFirewallLogService
{
public const PERMISSION_READ = 'firewall.tenant.logs.read';
public function __construct(
private readonly FirewallLogService $logs,
private readonly TenantContextInterface $tenant,
private readonly IdentityContextInterface $identity,
) {
}
public function query(array $filters, int $limit = 50, int $offset = 0): array
{
if (!$this->identity->hasPermission(self::PERMISSION_READ)) {
throw new \RuntimeException('Missing required permission: '.self::PERMISSION_READ);
}
return $this->logs->tenant($this->tenant->requireIdentifier(), $filters, $limit, $offset);
}
}
@@ -0,0 +1,154 @@
<?php
declare(strict_types=1);
namespace KTXC\Service;
use KTXC\Context\IdentityContextInterface;
use KTXC\Context\TenantContextInterface;
use KTXC\Models\Firewall\FirewallRuleObject;
final class TenantFirewallRuleService
{
public const PERMISSION_READ = 'firewall.tenant.rules.read';
public const PERMISSION_MANAGE = 'firewall.tenant.rules.manage';
public function __construct(
private readonly FirewallRuleManager $rules,
private readonly TenantContextInterface $tenant,
private readonly IdentityContextInterface $identity,
) {
}
public function listRules(bool $activeOnly = true): array
{
$this->requirePermission(self::PERMISSION_READ);
return $this->rules->list($this->scope(), $activeOnly);
}
public function queryRules(
string $status = 'active',
?string $type = null,
?string $action = null,
int $limit = 50,
int $offset = 0
): array {
$this->requirePermission(self::PERMISSION_READ);
return $this->rules->query($this->scope(), $status, $type, $action, $limit, $offset);
}
public function fetchRule(string $ruleId): ?FirewallRuleObject
{
$this->requirePermission(self::PERMISSION_READ);
return $this->rules->fetch($this->scope(), $ruleId);
}
public function createRule(
string $type,
string $action,
string $value,
string $reason,
?int $durationSeconds = null,
?string $currentIp = null,
bool $confirmCurrentIp = false
): FirewallRuleObject {
$this->requirePermission(self::PERMISSION_MANAGE);
return $this->rules->createManualRule(
$this->scope(),
$type,
$action,
$value,
$reason,
$this->identity->identifier(),
$durationSeconds,
$currentIp,
$confirmCurrentIp
);
}
public function effectivePolicy(): array
{
$this->requirePermission(self::PERMISSION_READ);
return $this->rules->effectivePolicy($this->tenant->requireIdentifier());
}
public function blockIp(string $ip, ?string $reason = null, ?int $durationSeconds = null): FirewallRuleObject
{
$this->requirePermission(self::PERMISSION_MANAGE);
return $this->rules->blockIp(
$this->scope(), $ip, $reason, $this->identity->identifier(), $durationSeconds
);
}
public function allowIp(string $ip, ?string $reason = null): FirewallRuleObject
{
$this->requirePermission(self::PERMISSION_MANAGE);
return $this->rules->allowIp($this->scope(), $ip, $reason, $this->identity->identifier());
}
public function blockIpRange(string $cidr, ?string $reason = null): FirewallRuleObject
{
$this->requirePermission(self::PERMISSION_MANAGE);
return $this->rules->blockIpRange($this->scope(), $cidr, $reason, $this->identity->identifier());
}
public function blockDevice(
string $fingerprint,
?string $reason = null,
?int $durationSeconds = null
): FirewallRuleObject {
$this->requirePermission(self::PERMISSION_MANAGE);
return $this->rules->blockDevice(
$this->scope(), $fingerprint, $reason, $this->identity->identifier(), $durationSeconds
);
}
public function disableRule(string $ruleId, string $reason): ?FirewallRuleObject
{
$this->requirePermission(self::PERMISSION_MANAGE);
return $this->rules->disableManual($this->scope(), $ruleId, $reason, $this->identity->identifier());
}
public function enableRule(
string $ruleId,
string $reason,
?string $currentIp = null,
bool $confirmCurrentIp = false
): ?FirewallRuleObject {
$this->requirePermission(self::PERMISSION_MANAGE);
return $this->rules->enableManual(
$this->scope(),
$ruleId,
$reason,
$this->identity->identifier(),
$currentIp,
$confirmCurrentIp
);
}
public function extendRule(string $ruleId, int $durationSeconds, string $reason): ?FirewallRuleObject
{
$this->requirePermission(self::PERMISSION_MANAGE);
return $this->rules->extendManual(
$this->scope(), $ruleId, $durationSeconds, $reason, $this->identity->identifier()
);
}
public function removeRule(string $ruleId, string $reason): ?FirewallRuleObject
{
$this->requirePermission(self::PERMISSION_MANAGE);
return $this->rules->removeManual($this->scope(), $ruleId, $reason, $this->identity->identifier());
}
private function scope(): FirewallRuleScope
{
return FirewallRuleScope::tenant($this->tenant->requireIdentifier());
}
private function requirePermission(string $permission): void
{
if (!$this->identity->hasPermission($permission)) {
throw new \RuntimeException("Missing required permission: {$permission}");
}
}
}
@@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
namespace KTXC\Service;
use KTXC\Context\IdentityContextInterface;
use KTXC\Context\TenantContextInterface;
final class TenantFirewallStatusService
{
public const PERMISSION_SETTINGS_READ = 'firewall.tenant.settings.read';
public const PERMISSION_SETTINGS_MANAGE = 'firewall.tenant.settings.manage';
public function __construct(
private readonly FirewallStatusService $status,
private readonly TenantContextInterface $tenant,
private readonly IdentityContextInterface $identity,
private readonly FirewallSettingsService $settings,
) {
}
public function metrics(?string $since = null): array
{
$this->requirePermission(TenantFirewallLogService::PERMISSION_READ);
return $this->status->tenantMetrics($this->tenant->requireIdentifier(), $since);
}
public function configuration(): array
{
$this->requirePermission(self::PERMISSION_SETTINGS_READ);
return $this->tenant->configuration()?->firewall()->jsonSerialize()
?? [
'enabled' => true,
'maxAuthFailures' => 5,
'authFailureWindow' => 300,
'autoBlockDuration' => 3600,
];
}
public function updateConfiguration(
bool $enabled,
int $maxAuthFailures,
int $authFailureWindow,
int $autoBlockDuration,
string $reason
): ?array {
$this->requirePermission(self::PERMISSION_SETTINGS_MANAGE);
return $this->settings->update(
$this->tenant->requireIdentifier(),
$enabled,
$maxAuthFailures,
$authFailureWindow,
$autoBlockDuration,
$reason,
$this->identity->identifier()
);
}
private function requirePermission(string $permission): void
{
if (!$this->identity->hasPermission($permission)) {
throw new \RuntimeException("Missing required permission: {$permission}");
}
}
}
+48 -11
View File
@@ -6,14 +6,19 @@ use KTXC\Models\Identity\User;
use KTXC\Context\IdentityContextInterface;
use KTXC\Context\TenantContextInterface;
use KTXC\Stores\UserAccountsStore;
use KTXC\User\Event\UserCreatedEvent;
use KTXC\User\Event\UserDeletingEvent;
use KTXC\User\Event\UserUpdatedEvent;
use KTXF\Event\EventDispatcherInterface;
class UserAccountsService
{
public function __construct(
private readonly TenantContextInterface $tenantContext,
private readonly IdentityContextInterface $identityContext,
private readonly UserAccountsStore $userStore
private readonly IdentityContextInterface $identityContext,
private readonly UserAccountsStore $userStore,
private readonly EventDispatcherInterface $events,
) {
}
@@ -65,17 +70,53 @@ class UserAccountsService
public function createUser(array $userData): array
{
return $this->userStore->createUser($this->tenantContext->identifier(), $userData);
$tenantId = $this->tenantContext->requireIdentifier();
$user = $this->userStore->createUser($tenantId, $userData);
$this->events->dispatch(UserCreatedEvent::fromUser(
$user,
$tenantId,
$this->identityContext->identifier(),
));
return $user;
}
public function updateUser(string $uid, array $updates): bool
public function updateUser(string $userId, array $updates): bool
{
return $this->userStore->updateUser($this->tenantContext->identifier(), $uid, $updates);
$tenantId = $this->tenantContext->requireIdentifier();
if (!$this->userStore->updateUser($tenantId, $userId, $updates)) {
return false;
}
$user = $this->userStore->fetchByIdentifier($tenantId, $userId);
if ($user === null) {
throw new \RuntimeException("Updated user '{$userId}' could not be retrieved.");
}
$this->events->dispatch(UserUpdatedEvent::fromUser(
$user,
$tenantId,
$this->identityContext->identifier(),
));
return true;
}
public function deleteUser(string $uid): bool
public function deleteUser(string $userId): bool
{
return $this->userStore->deleteUser($this->tenantContext->identifier(), $uid);
$tenantId = $this->tenantContext->requireIdentifier();
$user = $this->userStore->fetchByIdentifier($tenantId, $userId);
if ($user === null) {
return false;
}
$this->events->dispatch(UserDeletingEvent::fromUser(
$user,
$tenantId,
$this->identityContext->identifier(),
));
return $this->userStore->deleteUser($tenantId, $userId);
}
// =========================================================================
@@ -126,10 +167,6 @@ class UserAccountsService
return $this->userStore->storeSettings($this->tenantContext->identifier(), $this->identityContext->identifier(), $settings);
}
// =========================================================================
// Helper Methods
// =========================================================================
/**
* Check if a profile field is editable by the user
*
+389 -21
View File
@@ -5,6 +5,8 @@ declare(strict_types=1);
namespace KTXC\Stores;
use KTXC\Db\DataStore;
use KTXC\Db\ObjectId;
use KTXC\Db\UTCDateTime;
use KTXC\Models\Firewall\FirewallRuleObject;
use KTXC\Models\Firewall\FirewallLogObject;
@@ -15,28 +17,147 @@ class FirewallStore
{
protected const RULES_COLLECTION = 'firewall_rules';
protected const LOGS_COLLECTION = 'firewall_logs';
protected const BRUTE_FORCE_CLAIMS_COLLECTION = 'firewall_brute_force_claims';
protected const MAINTENANCE_COLLECTION = 'firewall_maintenance';
public function __construct(
protected readonly DataStore $dataStore
) {}
/**
* Install the indexes used by firewall enforcement, audit queries, and expiry.
*
* MongoDB createIndex is idempotent when the name and specification match.
*
* @return string[]
*/
public function ensureIndexes(): array
{
$rules = $this->dataStore->selectCollection(self::RULES_COLLECTION);
$logs = $this->dataStore->selectCollection(self::LOGS_COLLECTION);
$claims = $this->dataStore->selectCollection(self::BRUTE_FORCE_CLAIMS_COLLECTION);
return [
$rules->createIndex(
['scope' => 1, 'tenantId' => 1, 'enabled' => 1, 'expiresAt' => 1],
['name' => 'rules_by_scope_tenant_active']
),
$rules->createIndex(
['scope' => 1, 'tenantId' => 1, 'type' => 1, 'value' => 1, 'action' => 1, 'enabled' => 1, 'expiresAt' => 1],
['name' => 'rules_exact_lookup']
),
$rules->createIndex(
['scope' => 1, 'tenantId' => 1, 'createdAt' => -1],
['name' => 'rules_browse']
),
$logs->createIndex(
['tenantId' => 1, 'ipAddress' => 1, 'eventType' => 1, 'timestamp' => -1],
['name' => 'logs_auth_failures']
),
$logs->createIndex(
['tenantId' => 1, 'timestamp' => -1],
['name' => 'logs_tenant_timeline']
),
$logs->createIndex(
['tenantId' => 1, 'result' => 1, 'timestamp' => -1],
['name' => 'logs_blocked_counts']
),
$logs->createIndex(
['tenantId' => 1, 'eventType' => 1, 'timestamp' => -1],
['name' => 'logs_event_type']
),
$logs->createIndex(
['tenantId' => 1, 'ruleId' => 1, 'timestamp' => -1],
['name' => 'logs_rule']
),
$logs->createIndex(
['timestamp' => -1],
['name' => 'logs_global_timeline']
),
$claims->createIndex(
['expiresAt' => 1],
['name' => 'claims_expiry', 'expireAfterSeconds' => 0]
),
];
}
// ========================================
// Rule Operations
// ========================================
/**
* Query rules within one ownership scope.
*
* @return array{items: FirewallRuleObject[], total: int, limit: int, offset: int}
*/
public function queryRules(
string $scope,
?string $tenantId,
string $status,
?string $type,
?string $action,
int $limit,
int $offset
): array {
$filter = [
'scope' => $scope,
'tenantId' => $scope === FirewallRuleObject::SCOPE_SYSTEM ? null : $tenantId,
];
$now = self::bsonDate(new \DateTimeImmutable());
if ($status === 'active') {
$filter['enabled'] = true;
$filter['$or'] = [
['expiresAt' => null],
['expiresAt' => ['$gt' => $now]],
];
} elseif ($status === 'disabled') {
$filter['enabled'] = false;
} elseif ($status === 'expired') {
$filter['expiresAt'] = ['$ne' => null, '$lte' => $now];
}
if ($type !== null) {
$filter['type'] = $type;
}
if ($action !== null) {
$filter['action'] = $action;
}
$collection = $this->dataStore->selectCollection(self::RULES_COLLECTION);
$items = [];
foreach ($collection->find($filter, [
'sort' => ['createdAt' => -1, '_id' => -1],
'limit' => $limit,
'skip' => $offset,
]) as $entry) {
$items[] = (new FirewallRuleObject())->jsonDeserialize((array)$entry);
}
return [
'items' => $items,
'total' => $collection->countDocuments($filter),
'limit' => $limit,
'offset' => $offset,
];
}
/**
* List all rules for a tenant
*/
public function listRules(string $tenantId, bool $activeOnly = true): array
{
$filter = ['tenantId' => $tenantId];
$filter = [
'tenantId' => $tenantId,
'scope' => FirewallRuleObject::SCOPE_TENANT,
];
if ($activeOnly) {
$filter['enabled'] = true;
$filter['$or'] = [
$filter['$and'] = [[
'$or' => [
['expiresAt' => null],
['expiresAt' => ['$gt' => (new \DateTimeImmutable())->format(\DateTimeInterface::ATOM)]]
];
['expiresAt' => ['$gt' => self::bsonDate(new \DateTimeImmutable())]]
],
]];
}
$cursor = $this->dataStore->selectCollection(self::RULES_COLLECTION)->find($filter);
@@ -50,6 +171,26 @@ class FirewallStore
return $list;
}
public function listSystemRules(bool $activeOnly = true): array
{
$filter = ['scope' => FirewallRuleObject::SCOPE_SYSTEM, 'tenantId' => null];
if ($activeOnly) {
$filter['enabled'] = true;
$filter['$or'] = [
['expiresAt' => null],
['expiresAt' => ['$gt' => self::bsonDate(new \DateTimeImmutable())]],
];
}
$cursor = $this->dataStore->selectCollection(self::RULES_COLLECTION)->find($filter);
$list = [];
foreach ($cursor as $entry) {
$list[] = (new FirewallRuleObject())->jsonDeserialize((array)$entry);
}
return $list;
}
/**
* Find rules by IP address
*/
@@ -61,7 +202,7 @@ class FirewallStore
'enabled' => true,
'$or' => [
['expiresAt' => null],
['expiresAt' => ['$gt' => (new \DateTimeImmutable())->format(\DateTimeInterface::ATOM)]]
['expiresAt' => ['$gt' => self::bsonDate(new \DateTimeImmutable())]]
]
];
@@ -88,7 +229,7 @@ class FirewallStore
'enabled' => true,
'$or' => [
['expiresAt' => null],
['expiresAt' => ['$gt' => (new \DateTimeImmutable())->format(\DateTimeInterface::ATOM)]]
['expiresAt' => ['$gt' => self::bsonDate(new \DateTimeImmutable())]]
]
];
@@ -108,7 +249,7 @@ class FirewallStore
*/
public function fetchRule(string $id): ?FirewallRuleObject
{
$entry = $this->dataStore->selectCollection(self::RULES_COLLECTION)->findOne(['_id' => $id]);
$entry = $this->dataStore->selectCollection(self::RULES_COLLECTION)->findOne(self::ruleIdFilter($id));
if (!$entry) {
return null;
}
@@ -118,15 +259,33 @@ class FirewallStore
/**
* Check if exact IP rule exists
*/
public function findExactIpRule(string $tenantId, string $ipAddress, string $action): ?FirewallRuleObject
public function findExactIpRule(
?string $tenantId,
string $ipAddress,
string $action,
string $scope = FirewallRuleObject::SCOPE_TENANT
): ?FirewallRuleObject
{
$entry = $this->dataStore->selectCollection(self::RULES_COLLECTION)->findOne([
'tenantId' => $tenantId,
$filter = [
'type' => FirewallRuleObject::TYPE_IP,
'value' => $ipAddress,
'action' => $action,
'enabled' => true,
]);
'$or' => [
['expiresAt' => null],
['expiresAt' => ['$gt' => self::bsonDate(new \DateTimeImmutable())]],
],
];
if ($scope === FirewallRuleObject::SCOPE_SYSTEM) {
$filter['scope'] = FirewallRuleObject::SCOPE_SYSTEM;
$filter['tenantId'] = null;
} else {
$filter['tenantId'] = $tenantId;
$filter['scope'] = FirewallRuleObject::SCOPE_TENANT;
}
$entry = $this->dataStore->selectCollection(self::RULES_COLLECTION)->findOne($filter);
if (!$entry) {
return null;
@@ -139,6 +298,8 @@ class FirewallStore
*/
public function depositRule(FirewallRuleObject $rule): ?FirewallRuleObject
{
$rule->assertValidScopeOwnership();
if ($rule->getId()) {
return $this->updateRule($rule);
} else {
@@ -148,7 +309,7 @@ class FirewallStore
private function createRule(FirewallRuleObject $rule): ?FirewallRuleObject
{
$data = $rule->jsonSerialize();
$data = self::ruleDocument($rule);
unset($data['id']); // Remove id for insert
$result = $this->dataStore->selectCollection(self::RULES_COLLECTION)->insertOne($data);
@@ -163,11 +324,11 @@ class FirewallStore
return null;
}
$data = $rule->jsonSerialize();
$data = self::ruleDocument($rule);
unset($data['id']);
$this->dataStore->selectCollection(self::RULES_COLLECTION)->updateOne(
['_id' => $id],
self::ruleIdFilter($id),
['$set' => $data]
);
return $rule;
@@ -182,7 +343,7 @@ class FirewallStore
if (!$id) {
return;
}
$this->dataStore->selectCollection(self::RULES_COLLECTION)->deleteOne(['_id' => $id]);
$this->dataStore->selectCollection(self::RULES_COLLECTION)->deleteOne(self::ruleIdFilter($id));
}
/**
@@ -191,8 +352,10 @@ class FirewallStore
public function cleanupExpiredRules(): int
{
$result = $this->dataStore->selectCollection(self::RULES_COLLECTION)->deleteMany([
'expiresAt' => ['$lt' => (new \DateTimeImmutable())->format(\DateTimeInterface::ATOM)],
'expiresAt' => ['$ne' => null]
'expiresAt' => [
'$lt' => self::bsonDate(new \DateTimeImmutable()),
'$ne' => null,
],
]);
return $result->getDeletedCount();
@@ -202,12 +365,68 @@ class FirewallStore
// Log Operations
// ========================================
public function queryTenantLogs(
string $tenantId,
array $filters,
int $limit,
int $offset
): array {
return $this->queryLogs(['tenantId' => $tenantId], $filters, $limit, $offset);
}
public function querySystemLogs(
?string $tenantId,
array $filters,
int $limit,
int $offset
): array {
return $this->queryLogs($tenantId === null ? [] : ['tenantId' => $tenantId], $filters, $limit, $offset);
}
/** @return array{items: FirewallLogObject[], total: int, limit: int, offset: int} */
private function queryLogs(array $scopeFilter, array $filters, int $limit, int $offset): array
{
$filter = $scopeFilter;
foreach (['ipAddress', 'eventType', 'result', 'ruleId', 'ruleScope'] as $field) {
if (($filters[$field] ?? null) !== null) {
$filter[$field] = $filters[$field];
}
}
$timestamp = [];
if (($filters['from'] ?? null) instanceof \DateTimeInterface) {
$timestamp['$gte'] = self::bsonDate($filters['from']);
}
if (($filters['to'] ?? null) instanceof \DateTimeInterface) {
$timestamp['$lte'] = self::bsonDate($filters['to']);
}
if ($timestamp !== []) {
$filter['timestamp'] = $timestamp;
}
$collection = $this->dataStore->selectCollection(self::LOGS_COLLECTION);
$items = [];
foreach ($collection->find($filter, [
'sort' => ['timestamp' => -1, '_id' => -1],
'limit' => $limit,
'skip' => $offset,
]) as $entry) {
$items[] = (new FirewallLogObject())->jsonDeserialize((array)$entry);
}
return [
'items' => $items,
'total' => $collection->countDocuments($filter),
'limit' => $limit,
'offset' => $offset,
];
}
/**
* Log a firewall event
*/
public function createLog(FirewallLogObject $log): FirewallLogObject
{
$data = $log->jsonSerialize();
$data = self::logDocument($log);
unset($data['id']);
$result = $this->dataStore->selectCollection(self::LOGS_COLLECTION)->insertOne($data);
@@ -215,6 +434,30 @@ class FirewallStore
return $log;
}
/**
* Insert an event-backed log once, using the event ID as MongoDB's unique key.
*/
public function createLogOnce(FirewallLogObject $log): bool
{
$eventId = $log->getEventId();
if ($eventId === null || $eventId === '') {
throw new \InvalidArgumentException('Idempotent firewall logs require an event ID.');
}
$data = self::logDocument($log);
unset($data['id']);
$data['_id'] = $eventId;
$result = $this->dataStore->selectCollection(self::LOGS_COLLECTION)->updateOne(
['_id' => $eventId],
['$setOnInsert' => $data],
['upsert' => true]
);
$log->setId($eventId);
return $result->getUpsertedCount() === 1;
}
/**
* Get logs for a tenant with optional filters
*/
@@ -270,10 +513,50 @@ class FirewallStore
'tenantId' => $tenantId,
'ipAddress' => $ipAddress,
'eventType' => FirewallLogObject::EVENT_AUTH_FAILURE,
'timestamp' => ['$gte' => $since->format(\DateTimeInterface::ATOM)]
'timestamp' => ['$gte' => self::bsonDate($since)]
]);
}
/**
* Atomically claim responsibility for responding to a tenant/IP brute-force incident.
*/
public function claimBruteForce(
string $tenantId,
string $ipAddress,
int $claimDurationSeconds
): bool {
if ($claimDurationSeconds < 1) {
throw new \InvalidArgumentException('Brute-force claim duration must be greater than zero.');
}
$now = new \DateTimeImmutable();
$claimId = hash('sha256', $tenantId."\0".$ipAddress);
$collection = $this->dataStore->selectCollection(self::BRUTE_FORCE_CLAIMS_COLLECTION);
$collection->deleteOne([
'_id' => $claimId,
'expiresAt' => ['$lte' => self::bsonDate($now)],
]);
try {
$collection->insertOne([
'_id' => $claimId,
'tenantId' => $tenantId,
'ipAddress' => $ipAddress,
'createdAt' => self::bsonDate($now),
'expiresAt' => self::bsonDate($now->modify("+{$claimDurationSeconds} seconds")),
]);
} catch (\MongoDB\Driver\Exception\BulkWriteException $error) {
if ($error->getCode() === 11000) {
return false;
}
throw $error;
}
return true;
}
/**
* Get blocked requests count for dashboard
*/
@@ -287,12 +570,27 @@ class FirewallStore
];
if ($since !== null) {
$filter['timestamp'] = ['$gte' => $since->format(\DateTimeInterface::ATOM)];
$filter['timestamp'] = ['$gte' => self::bsonDate($since)];
}
return $this->dataStore->selectCollection(self::LOGS_COLLECTION)->countDocuments($filter);
}
public function countSystemBlockedRequests(
?string $tenantId = null,
?\DateTimeImmutable $since = null
): int {
$filter = ['result' => FirewallLogObject::RESULT_BLOCKED];
if ($tenantId !== null) {
$filter['tenantId'] = $tenantId;
}
if ($since !== null) {
$filter['timestamp'] = ['$gte' => self::bsonDate($since)];
}
return $this->dataStore->selectCollection(self::LOGS_COLLECTION)->countDocuments($filter);
}
/**
* Clean up old logs
*/
@@ -301,9 +599,79 @@ class FirewallStore
$cutoff = (new \DateTimeImmutable())->modify("-{$daysToKeep} days");
$result = $this->dataStore->selectCollection(self::LOGS_COLLECTION)->deleteMany([
'timestamp' => ['$lt' => $cutoff->format(\DateTimeInterface::ATOM)]
'timestamp' => ['$lt' => self::bsonDate($cutoff)]
]);
return $result->getDeletedCount();
}
public function cleanupExpiredBruteForceClaims(): int
{
$result = $this->dataStore
->selectCollection(self::BRUTE_FORCE_CLAIMS_COLLECTION)
->deleteMany([
'expiresAt' => ['$lte' => self::bsonDate(new \DateTimeImmutable())],
]);
return $result->getDeletedCount();
}
public function recordMaintenanceStatus(
\DateTimeImmutable $startedAt,
\DateTimeImmutable $completedAt,
string $status,
array $result,
?string $error = null
): void {
$this->dataStore->selectCollection(self::MAINTENANCE_COLLECTION)->updateOne(
['_id' => 'cleanup'],
['$set' => [
'startedAt' => self::bsonDate($startedAt),
'completedAt' => self::bsonDate($completedAt),
'status' => $status,
'result' => $result,
'error' => $error,
]],
['upsert' => true]
);
}
public function maintenanceStatus(): ?array
{
return $this->dataStore
->selectCollection(self::MAINTENANCE_COLLECTION)
->findOne(['_id' => 'cleanup']);
}
private static function ruleDocument(FirewallRuleObject $rule): array
{
$data = $rule->jsonSerialize();
$data['createdAt'] = self::nullableBsonDate($rule->getCreatedAt());
$data['expiresAt'] = self::nullableBsonDate($rule->getExpiresAt());
return $data;
}
private static function logDocument(FirewallLogObject $log): array
{
$data = $log->jsonSerialize();
$data['timestamp'] = self::nullableBsonDate($log->getTimestamp());
return $data;
}
private static function nullableBsonDate(?\DateTimeInterface $date): ?UTCDateTime
{
return $date === null ? null : self::bsonDate($date);
}
private static function bsonDate(\DateTimeInterface $date): UTCDateTime
{
return UTCDateTime::fromDateTime($date);
}
private static function ruleIdFilter(string $id): array
{
return ['_id' => ObjectId::isValid($id) ? ObjectId::fromString($id) : $id];
}
}
+32
View File
@@ -77,6 +77,38 @@ class TenantStore
$this->dataStore->selectCollection(self::COLLECTION_NAME)->deleteOne(['_id' => new ObjectId($id)]);
}
/**
* Atomically creates or replaces one logical store reference.
*
* @param array{provider: string, service: string|int, namespace: string} $reference
*/
public function storeConfigurationStore(string $identifier, string $name, array $reference): bool
{
$result = $this->dataStore->selectCollection(self::COLLECTION_NAME)->updateOne(
['identifier' => $identifier],
['$set' => ["configuration.stores.{$name}" => $reference]],
);
return $result->getMatchedCount() > 0;
}
/**
* Atomically removes one logical store reference.
*/
public function removeConfigurationStore(string $identifier, string $name): ?bool
{
$result = $this->dataStore->selectCollection(self::COLLECTION_NAME)->updateOne(
['identifier' => $identifier],
['$unset' => ["configuration.stores.{$name}" => '']],
);
if ($result->getMatchedCount() === 0) {
return null;
}
return $result->getModifiedCount() > 0;
}
// =========================================================================
// Settings Operations
// =========================================================================
@@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
namespace KTXC\SystemStore;
use KTXC\Stores\TenantStore;
use KTXF\SystemStore\StoreReference;
use KTXF\SystemStore\SystemStoreException;
/**
* Superuser-facing configuration operations for tenant logical stores.
*/
class SystemStoreConfigurationService
{
public function __construct(private readonly TenantStore $tenants)
{
}
/** @return array<string, StoreReference> */
public function list(string $tenantId): array
{
$tenant = $this->tenants->fetch($tenantId);
if ($tenant === null) {
throw new SystemStoreException("Tenant '{$tenantId}' was not found");
}
return $tenant->getConfiguration()->stores()->all();
}
public function set(
string $tenantId,
string $name,
string $provider,
string|int $service,
string $namespace,
): StoreReference {
self::validateName($name);
$reference = new StoreReference($provider, $service, $namespace);
if (!$this->tenants->storeConfigurationStore($tenantId, $name, $reference->toArray())) {
throw new SystemStoreException("Tenant '{$tenantId}' was not found");
}
return $reference;
}
public function remove(string $tenantId, string $name): bool
{
self::validateName($name);
$removed = $this->tenants->removeConfigurationStore($tenantId, $name);
if ($removed === null) {
throw new SystemStoreException("Tenant '{$tenantId}' was not found");
}
return $removed;
}
private static function validateName(string $name): void
{
if (preg_match('/^[a-z][a-z0-9-]*$/', $name) !== 1) {
throw new \InvalidArgumentException('Logical store names must use lowercase letters, numbers, and hyphens');
}
}
}
+167
View File
@@ -0,0 +1,167 @@
<?php
declare(strict_types=1);
namespace KTXC\SystemStore;
use KTXC\Resource\ProviderManager;
use KTXC\Service\TenantService;
use KTXF\Resource\BinaryResource;
use KTXF\Resource\Provider\ProviderInterface;
use KTXF\Resource\SystemIdentity;
use KTXF\SystemStore\BlobInfo;
use KTXF\SystemStore\InvalidKeyException;
use KTXF\SystemStore\Provider\ProviderBaseInterface;
use KTXF\SystemStore\Service\SystemStoreServiceInterface;
use KTXF\SystemStore\StoreReference;
use KTXF\SystemStore\SystemStoreException;
use KTXF\SystemStore\SystemStoreManagerInterface;
use KTXF\SystemStore\WriteCondition;
final readonly class SystemStoreManager implements SystemStoreManagerInterface
{
public function __construct(
private TenantService $tenants,
private ProviderManager $providers,
) {
}
public function stat(string $tenantId, string $store, string $key): ?BlobInfo
{
[$service, $reference] = $this->resolve($tenantId, $store);
$info = $service->stat($this->qualify($reference, $key));
return $info === null ? null : $this->logicalInfo($info, $reference);
}
public function read(string $tenantId, string $store, string $key): ?BinaryResource
{
[$service, $reference] = $this->resolve($tenantId, $store);
return $service->read($this->qualify($reference, $key));
}
public function write(
string $tenantId,
string $store,
string $key,
BinaryResource $content,
array $metadata = [],
?WriteCondition $condition = null,
): BlobInfo {
[$service, $reference] = $this->resolve($tenantId, $store);
$info = $service->write(
$this->qualify($reference, $key),
$content,
$metadata,
$condition,
);
return $this->logicalInfo($info, $reference);
}
public function delete(
string $tenantId,
string $store,
string $key,
?WriteCondition $condition = null,
): bool {
[$service, $reference] = $this->resolve($tenantId, $store);
return $service->delete($this->qualify($reference, $key), $condition);
}
public function list(string $tenantId, string $store, string $prefix = ''): iterable
{
[$service, $reference] = $this->resolve($tenantId, $store);
$physicalPrefix = $reference->namespace . '/';
if ($prefix !== '') {
$physicalPrefix .= $this->normalizeKey($prefix, true);
}
return $this->logicalItems($service->list($physicalPrefix), $reference);
}
/** @return array{SystemStoreServiceInterface, StoreReference} */
private function resolve(string $tenantId, string $store): array
{
$tenant = $this->tenants->fetchById($tenantId);
if ($tenant === null) {
throw new SystemStoreException("Tenant '{$tenantId}' was not found");
}
$reference = $tenant->getConfiguration()->stores()->store($store);
if ($reference === null) {
throw new SystemStoreException("System store '{$store}' is not configured for tenant '{$tenantId}'");
}
$provider = $this->providers->resolve(ProviderInterface::TYPE_SYSTEM_STORE, $reference->provider);
if (!$provider instanceof ProviderBaseInterface) {
throw new SystemStoreException("System-store provider '{$reference->provider}' is unavailable or incompatible");
}
$service = $provider->serviceFetch($tenantId, SystemIdentity::USER, $reference->service);
if (!$service instanceof SystemStoreServiceInterface) {
throw new SystemStoreException("System-store service '{$reference->service}' is unavailable or incompatible");
}
return [$service, $reference];
}
private function qualify(StoreReference $reference, string $key): string
{
return $reference->namespace . '/' . $this->normalizeKey($key);
}
private function normalizeKey(string $key, bool $allowTrailingSlash = false): string
{
if (
$key === ''
|| str_starts_with($key, '/')
|| (!$allowTrailingSlash && str_ends_with($key, '/'))
|| str_contains($key, '\\')
|| str_contains($key, "\0")
) {
throw new InvalidKeyException('System-store keys must be non-empty normalized relative keys');
}
$segments = explode('/', $key);
if ($allowTrailingSlash && end($segments) === '') {
array_pop($segments);
}
if (in_array('', $segments, true) || in_array('.', $segments, true) || in_array('..', $segments, true)) {
throw new InvalidKeyException('System-store keys cannot contain empty or traversal segments');
}
return $key;
}
private function logicalInfo(BlobInfo $info, StoreReference $reference): BlobInfo
{
$prefix = $reference->namespace . '/';
if (!str_starts_with($info->key, $prefix)) {
throw new SystemStoreException('System-store provider returned a blob outside the configured namespace');
}
return new BlobInfo(
key: substr($info->key, strlen($prefix)),
mimeType: $info->mimeType,
size: $info->size,
etag: $info->etag,
modifiedAt: $info->modifiedAt,
attributes: $info->attributes,
);
}
/**
* @param iterable<BlobInfo> $items
* @return iterable<BlobInfo>
*/
private function logicalItems(iterable $items, StoreReference $reference): iterable
{
foreach ($items as $item) {
if (!$item instanceof BlobInfo) {
throw new SystemStoreException('System-store provider returned invalid listing metadata');
}
yield $this->logicalInfo($item, $reference);
}
}
}
+9
View File
@@ -0,0 +1,9 @@
<?php
declare(strict_types=1);
namespace KTXC\User\Event;
final class UserCreatedEvent extends UserEvent
{
}
@@ -0,0 +1,9 @@
<?php
declare(strict_types=1);
namespace KTXC\User\Event;
final class UserDeletingEvent extends UserEvent
{
}
+94
View File
@@ -0,0 +1,94 @@
<?php
declare(strict_types=1);
namespace KTXC\User\Event;
use KTXF\Event\Event;
abstract class UserEvent extends Event
{
final public function __construct(
private readonly string $userIdentifier,
private readonly string $userIdentity,
private readonly string $userLabel,
private readonly bool $userEnabled,
private readonly array $userRoles,
private readonly string $tenantIdentifier,
private readonly ?string $actorIdentifier = null,
) {
if ($userIdentifier === '') {
throw new \InvalidArgumentException('User lifecycle events require a user ID.');
}
if ($userIdentity === '') {
throw new \InvalidArgumentException('User lifecycle events require a user identity.');
}
if ($tenantIdentifier === '') {
throw new \InvalidArgumentException('User lifecycle events require a tenant ID.');
}
parent::__construct(
static::class,
[
'identifier' => $userIdentifier,
'identity' => $userIdentity,
'label' => $userLabel,
'roles' => $userRoles,
'enabled' => $userEnabled,
],
$tenantIdentifier,
$actorIdentifier,
);
}
public static function fromUser(
array $user,
string $tenantIdentifier,
?string $actorIdentifier = null,
): static {
return new static(
(string) ($user['uid'] ?? ''),
(string) ($user['identity'] ?? ''),
(string) ($user['label'] ?? $user['identity'] ?? ''),
(bool) ($user['enabled'] ?? true),
array_values((array) ($user['roles'] ?? [])),
$tenantIdentifier,
$actorIdentifier,
);
}
public function userIdentifier(): string
{
return $this->userIdentifier;
}
public function tenantIdentifier(): string
{
return $this->tenantIdentifier;
}
public function userIdentity(): string
{
return $this->userIdentity;
}
public function userLabel(): string
{
return $this->userLabel;
}
public function userRoles(): array
{
return $this->userRoles;
}
public function userEnabled(): bool
{
return $this->userEnabled;
}
public function actorIdentifier(): ?string
{
return $this->actorIdentifier;
}
}
+9
View File
@@ -0,0 +1,9 @@
<?php
declare(strict_types=1);
namespace KTXC\User\Event;
final class UserUpdatedEvent extends UserEvent
{
}
+1 -4
View File
@@ -88,12 +88,9 @@ const userAvatar = computed(() => userStore.getProfileField('avatar') || default
<template v-slot:activator="{ props }">
<v-btn class="profileBtn" variant="text" rounded="sm" v-bind="props">
<div class="d-flex align-center">
<v-avatar class="mr-sm-2 mr-0" size="32">
<v-avatar size="32">
<v-img :src="userAvatar" :alt="userAuth?.label || 'User'" cover />
</v-avatar>
<h6 class="text-subtitle-1 mb-0 d-sm-block d-none">
{{ userAuth?.label }}
</h6>
</div>
</v-btn>
</template>
+50 -39
View File
@@ -1,7 +1,8 @@
<script setup lang="ts">
import { computed } from 'vue';
import { computed, watch } from 'vue';
import { useLayoutStore, type MenuMode } from '@KTXC/stores/layoutStore';
import { useIntegrationStore } from '@KTXC/stores/integrationStore';
import type { IntegrationPointType } from '@KTXC/types/integrationTypes';
import { useL10n } from '@KTXC/composables/useL10n';
import Logo from '@KTXC/layouts/logo/LogoDark.vue';
import SystemMenuGroupStatic from './LayoutSystemMenuGroupStatic.vue';
@@ -12,25 +13,33 @@ const layoutStore = useLayoutStore();
const integrationStore = useIntegrationStore();
const { t } = useL10n('core');
const menuPointByMode: Record<MenuMode, IntegrationPointType> = {
apps: 'app_menu',
'user-settings': 'user_settings_menu',
'admin-settings': 'admin_settings_menu',
};
// Get all entries based on current menu mode
const menuEntries = computed(() => {
switch (layoutStore.menuMode) {
case 'user-settings':
return integrationStore.getPoint('user_settings_menu');
case 'admin-settings':
return integrationStore.getPoint('admin_settings_menu');
case 'apps':
default:
return integrationStore.getPoint('app_menu');
}
const menuEntries = computed(() => integrationStore.getPoint(menuPointByMode[layoutStore.menuMode]));
// Only show menu modes that currently have visible items.
const menuModes = computed((): Array<{ value: MenuMode; icon: string; label: string }> => {
const modes: Array<{ value: MenuMode; icon: string; label: string }> = [
{ value: 'apps', icon: 'mdi-view-dashboard', label: t('systemMenu.apps', 'Applications') },
{ value: 'user-settings', icon: 'mdi-account-cog', label: t('systemMenu.personalSettings', 'Settings') },
{ value: 'admin-settings', icon: 'mdi-shield-crown', label: t('systemMenu.adminSettings', 'System') },
];
return modes.filter(mode => integrationStore.getPoint(menuPointByMode[mode.value]).length > 0);
});
// Static list of menu modes shown as icon buttons
const menuModes = computed((): Array<{ value: MenuMode; icon: string; label: string }> => [
{ value: 'apps', icon: 'mdi-view-dashboard', label: t('systemMenu.apps', 'Applications') },
{ value: 'user-settings', icon: 'mdi-account-cog', label: t('systemMenu.personalSettings', 'Settings') },
{ value: 'admin-settings', icon: 'mdi-shield-crown', label: t('systemMenu.adminSettings', 'System') },
]);
// If the active menu becomes empty (for example, after a module is disabled),
// move to the first menu that still has content.
watch(menuModes, (availableModes) => {
if (availableModes.length > 0 && !availableModes.some(mode => mode.value === layoutStore.menuMode)) {
layoutStore.setMenuMode(availableModes[0].value);
}
}, { immediate: true });
</script>
<script lang="ts">
@@ -84,28 +93,30 @@ export default {
<!-- Menu Mode Switcher -->
<template v-slot:append>
<v-divider />
<div class="menu-mode-switcher d-flex justify-space-around align-center py-2">
<v-tooltip
v-for="mode in menuModes"
:key="mode.value"
location="right"
>
<template v-slot:activator="{ props }">
<v-btn
v-bind="props"
icon
variant="text"
density="comfortable"
:color="layoutStore.menuMode === mode.value ? 'primary' : undefined"
:class="['menu-mode-btn', { 'menu-mode-btn--active': layoutStore.menuMode === mode.value }]"
@click="layoutStore.setMenuMode(mode.value)"
>
<v-icon>{{ mode.icon }}</v-icon>
</v-btn>
</template>
<span>{{ mode.label }}</span>
</v-tooltip>
<div v-if="menuModes.length">
<v-divider />
<div class="menu-mode-switcher d-flex justify-space-around align-center py-2">
<v-tooltip
v-for="mode in menuModes"
:key="mode.value"
location="right"
>
<template v-slot:activator="{ props }">
<v-btn
v-bind="props"
icon
variant="text"
density="comfortable"
:color="layoutStore.menuMode === mode.value ? 'primary' : undefined"
:class="['menu-mode-btn', { 'menu-mode-btn--active': layoutStore.menuMode === mode.value }]"
@click="layoutStore.setMenuMode(mode.value)"
>
<v-icon>{{ mode.icon }}</v-icon>
</v-btn>
</template>
<span>{{ mode.label }}</span>
</v-tooltip>
</div>
</div>
</template>
</v-navigation-drawer>
+9 -18
View File
@@ -3,13 +3,11 @@ import { computed } from 'vue';
import { useUserStore } from '@KTXC/stores/userStore';
import { useIntegrationStore } from '@KTXC/stores/integrationStore';
import { useLayoutStore } from '@KTXC/stores/layoutStore';
import { useRouter } from 'vue-router';
import { useL10n, t as tGlobal } from '@KTXC/composables/useL10n';
import defaultAvatar from '@KTXC/assets/images/users/avatar-1.png';
const { t } = useL10n('core');
const router = useRouter();
const userStore = useUserStore();
const integrationStore = useIntegrationStore();
const layoutStore = useLayoutStore();
@@ -43,12 +41,6 @@ const cycleTheme = () => {
layoutStore.setTheme(nextThemeMode.value);
};
// Navigate to settings
const goToSettings = () => {
layoutStore.setMenuMode('settings');
// Navigate to first settings item or a default settings route
router.push('/modules'); // TODO: Make this dynamic based on first settings menu item
};
</script>
<template>
@@ -62,9 +54,9 @@ const goToSettings = () => {
<v-img :src="userAvatar" :alt="userName" cover />
</v-avatar>
<div class="flex-grow-1">
<h6 class="text-h6 mb-0 font-weight-medium">
<h5 class="user-menu-name mb-0 font-weight-bold">
{{ userName }}
</h6>
</h5>
<p class="text-caption mb-0 text-medium-emphasis">{{ userEmail }}</p>
</div>
</div>
@@ -98,14 +90,6 @@ const goToSettings = () => {
<v-list-item-title class="text-h6">{{ t(MODE_PRESENTATION[nextThemeMode].l10n, MODE_PRESENTATION[nextThemeMode].label) }}</v-list-item-title>
</v-list-item>
<!-- Go to Settings -->
<v-list-item @click="goToSettings" color="primary" rounded="0">
<template v-slot:prepend>
<v-icon>mdi-cog-outline</v-icon>
</template>
<v-list-item-title class="text-h6">{{ t('userMenu.settings', 'Settings') }}</v-list-item-title>
</v-list-item>
<v-divider class="my-2" />
<!-- Logout -->
@@ -119,3 +103,10 @@ const goToSettings = () => {
</perfect-scrollbar>
</div>
</template>
<style scoped>
.user-menu-name {
font-size: 18px !important;
line-height: 1.2;
}
</style>
+4
View File
@@ -156,6 +156,10 @@ export const useIntegrationStore = defineStore('integrationStore', {
return Array.from(point.items.values())
.filter(entry => entry.visible !== false)
.map(entry => 'items' in entry
? { ...entry, items: entry.items.filter(item => item.visible !== false) }
: entry)
.filter(entry => !('items' in entry) || entry.items.length > 0)
.sort((a, b) => (a.priority ?? 100) - (b.priority ?? 100));
},
+2 -2
View File
@@ -32,7 +32,7 @@ export const useLayoutStore = defineStore('layout', () => {
}
const sidebarDrawer = ref<boolean>(booleanSetting('sidebar_drawer', true));
const miniSidebar = ref<boolean>(booleanSetting('mini_sidebar', false));
const miniSidebar = ref<boolean>(booleanSetting('mini_sidebar', true));
const menuMode = ref<MenuMode>('apps');
// Theme mode - user choice, falling back to the tenant default
@@ -60,7 +60,7 @@ export const useLayoutStore = defineStore('layout', () => {
hydratingFromSettings = true;
try {
sidebarDrawer.value = booleanSetting('sidebar_drawer', true);
miniSidebar.value = booleanSetting('mini_sidebar', false);
miniSidebar.value = booleanSetting('mini_sidebar', true);
theme.value = initialTheme();
} finally {
hydratingFromSettings = false;
+31 -20
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue';
import { ref, onMounted, computed, watch, nextTick } from 'vue';
import { useRoute } from 'vue-router';
import { useUserStore } from '@KTXC/stores/userStore';
import { authenticationService } from '@KTXC/services/authenticationService';
@@ -15,6 +15,7 @@ type LoginPhase = 'identity' | 'method' | 'mfa';
// Form state
const identity = ref('');
const authResponse = ref(''); // password, code, etc.
const authInput = ref<{ focus: () => void } | null>(null);
const showPassword = ref(false);
const rememberMe = ref(false);
@@ -60,21 +61,19 @@ const pageTitle = computed(() => {
});
// Input label/type based on selected method
const isPasswordMethod = computed(() => selectedMethod.value?.id === 'password');
const authInputLabel = computed(() => {
if (!selectedMethod.value) return 'Password';
return selectedMethod.value.method === 'credential' ? 'Password' : 'Verification Code';
return isPasswordMethod.value ? 'Password' : 'Verification Code';
});
const authInputType = computed(() => {
if (!selectedMethod.value) return 'password';
return selectedMethod.value.method === 'credential' ? 'password' : 'text';
return isPasswordMethod.value ? 'password' : 'text';
});
// Validation rules
const identityRules = [
(v: string) => !!v.trim() || 'Email is required',
(v: string) => !/\s/.test(v.trim()) || 'Email must not contain spaces',
(v: string) => /.+@.+\..+/.test(v.trim()) || 'Email must be valid'
(v: string) => !!v.trim() || 'Login ID is required',
];
const authResponseRules = [
@@ -117,6 +116,9 @@ onMounted(async () => {
// Watch for method selection changes (for challenge-based methods)
watch(selectedMethod, async (newMethod) => {
await nextTick();
authInput.value?.focus();
if (newMethod && newMethod.method === 'challenge' && !challengeSent.value) {
// Initiate challenge for methods that need it (SMS, email, TOTP)
await initiateChallenge(newMethod.id);
@@ -313,7 +315,16 @@ function backToIdentity() {
}
function getMethodIcon(method: AuthenticationMethod): string {
if (method.icon) return method.icon;
if (method.icon?.startsWith('mdi-') || method.icon?.startsWith('$')) {
return method.icon;
}
// Authentication providers may return a bare Material Design icon name
// (for example, "lock" or "mail") instead of Vuetify's "mdi-*" form.
if (method.icon && /^[a-z0-9-]+$/i.test(method.icon)) {
return `mdi-${method.icon}`;
}
switch (method.method) {
case 'credential': return 'mdi-key';
case 'challenge': return 'mdi-shield-check';
@@ -351,16 +362,15 @@ function getMethodIcon(method: AuthenticationMethod): string {
v-slot="{ errors, isSubmitting }"
>
<div class="mb-6">
<v-label>Email Address</v-label>
<v-text-field
v-model="identity"
:rules="identityRules"
class="mt-2"
aria-label="Login ID"
required
hide-details="auto"
variant="outlined"
color="primary"
autocomplete="email"
autocomplete="username"
autofocus
></v-text-field>
</div>
@@ -391,7 +401,7 @@ function getMethodIcon(method: AuthenticationMethod): string {
size="large"
@click="initiateSsoLogin(method.id)"
>
<v-icon v-if="method.icon" start>{{ method.icon }}</v-icon>
<v-icon start>{{ getMethodIcon(method) }}</v-icon>
{{ method.label }}
</v-btn>
</div>
@@ -445,18 +455,18 @@ function getMethodIcon(method: AuthenticationMethod): string {
v-slot="{ errors, isSubmitting }"
>
<div class="mb-6">
<v-label>{{ authInputLabel }}</v-label>
<v-text-field
ref="authInput"
v-model="authResponse"
:rules="authResponseRules"
:type="authInputType === 'password' && !showPassword ? 'password' : 'text'"
class="mt-2"
:aria-label="authInputLabel"
required
hide-details="auto"
variant="outlined"
color="primary"
:autocomplete="selectedMethod?.method === 'credential' ? 'current-password' : 'one-time-code'"
:inputmode="selectedMethod?.method !== 'credential' ? 'numeric' : undefined"
:autocomplete="isPasswordMethod ? 'current-password' : 'off'"
:inputmode="isPasswordMethod ? undefined : 'numeric'"
autofocus
>
<template v-if="authInputType === 'password'" v-slot:append-inner>
@@ -470,7 +480,7 @@ function getMethodIcon(method: AuthenticationMethod): string {
</v-text-field>
</div>
<div v-if="selectedMethod?.method === 'credential'" class="d-flex align-center mt-4 mb-7 mb-sm-0">
<div v-if="isPasswordMethod" class="d-flex align-center mt-4 mb-7 mb-sm-0">
<v-checkbox
v-model="rememberMe"
label="Keep me logged in"
@@ -493,7 +503,7 @@ function getMethodIcon(method: AuthenticationMethod): string {
size="large"
type="submit"
>
{{ selectedMethod?.method === 'credential' ? 'Login' : 'Verify' }}
{{ isPasswordMethod ? 'Login' : 'Verify' }}
</v-btn>
<v-btn
@@ -534,6 +544,7 @@ function getMethodIcon(method: AuthenticationMethod): string {
<div class="mb-6">
<v-label>Verification Code</v-label>
<v-text-field
ref="authInput"
v-model="authResponse"
:rules="authResponseRules"
type="text"
@@ -542,7 +553,7 @@ function getMethodIcon(method: AuthenticationMethod): string {
hide-details="auto"
variant="outlined"
color="primary"
autocomplete="one-time-code"
autocomplete="off"
inputmode="numeric"
autofocus
></v-text-field>
+2
View File
@@ -0,0 +1,2 @@
# Install in /etc/cron.d/ktrix-firewall after adjusting the user/path if needed.
*/15 * * * * www-data cd /var/www/ktrix/main && bin/console firewall:maintenance
+24
View File
@@ -33,6 +33,30 @@ require_command()
fi
}
# Cron runs with a bare PATH, so nvm-installed npm (added to PATH only by
# .bashrc sourcing nvm.sh in an interactive shell) is invisible here even
# though it works fine when this script is run by hand. Resolve nvm's
# current npm via bash (nvm.sh is not POSIX sh compatible) and prepend it,
# so a later `nvm use`/`nvm install` doesn't require updating this script
# or the crontab.
ensure_npm_on_path()
{
command -v npm >/dev/null 2>&1 && return 0
nvm_dir=${NVM_DIR:-${HOME:-/root}/.nvm}
[ -s "$nvm_dir/nvm.sh" ] || return 0
command -v bash >/dev/null 2>&1 || return 0
npm_path=$(bash -c ". \"\$1/nvm.sh\" >/dev/null 2>&1 && command -v npm" _ "$nvm_dir" 2>/dev/null) || return 0
[ -n "$npm_path" ] || return 0
PATH=$(dirname -- "$npm_path"):$PATH
export PATH
log "Resolved npm via nvm: $npm_path"
}
ensure_npm_on_path
git_in()
{
repository=$1
+47 -64
View File
@@ -10,76 +10,76 @@ namespace KTXF\Event;
class Event
{
private bool $propagationStopped = false;
private array $data = [];
private float $timestamp;
private ?string $tenantId = null;
private ?string $identityId = null;
private readonly array $context;
private readonly float $timestamp;
private readonly string $identifier;
public function __construct(
private readonly string $name,
array $data = []
private readonly string $label,
array $context = [],
private readonly ?string $tenantIdentifier = null,
private readonly ?string $actorIdentity = null,
) {
$this->data = $data;
self::validateContext($context);
$this->context = $context;
$this->timestamp = microtime(true);
$this->identifier = bin2hex(random_bytes(16));
}
/**
* Get the event name
* Get the event label
*/
public function getName(): string
public function label(): string
{
return $this->name;
return $this->label;
}
/**
* Get a data value by key
* Get a context value by key
*/
public function get(string $key, mixed $default = null): mixed
{
return $this->data[$key] ?? $default;
return $this->context[$key] ?? $default;
}
/**
* Set a data value
*/
public function set(string $key, mixed $value): self
{
$this->data[$key] = $value;
return $this;
}
/**
* Check if a data key exists
* Check if a context key exists
*/
public function has(string $key): bool
{
return array_key_exists($key, $this->data);
return array_key_exists($key, $this->context);
}
/**
* Get all data
* Get the event context
*/
public function getData(): array
public function context(): array
{
return $this->data;
return $this->context;
}
/**
* Alias for getData() for backward compatibility
* Get all event context
*/
public function all(): array
{
return $this->data;
return $this->context;
}
/**
* Get the event timestamp
*/
public function getTimestamp(): float
public function timestamp(): float
{
return $this->timestamp;
}
public function identifier(): string
{
return $this->identifier;
}
/**
* Stop event propagation to subsequent listeners
*/
@@ -99,48 +99,31 @@ class Event
/**
* Get tenant ID for multi-tenant context
*/
public function getTenantId(): ?string
public function tenantIdentifier(): ?string
{
return $this->tenantId;
return $this->tenantIdentifier;
}
/**
* Set tenant ID for multi-tenant context
* Get the identity of the actor who triggered the event
*/
public function setTenantId(?string $tenantId): self
public function actorIdentity(): ?string
{
$this->tenantId = $tenantId;
return $this;
return $this->actorIdentity;
}
/**
* Get identity ID (user who triggered the event)
*/
public function getIdentityId(): ?string
private static function validateContext(array $context): void
{
return $this->identityId;
foreach ($context as $value) {
if (is_array($value)) {
self::validateContext($value);
continue;
}
if ($value !== null && !is_scalar($value)) {
throw new \InvalidArgumentException(
'Event context must contain only scalar, null, or array values.',
);
}
}
}
/**
* Set identity ID
*/
public function setIdentityId(?string $identityId): self
{
$this->identityId = $identityId;
return $this;
}
/**
* Convert event to array for serialization/logging
*/
public function toArray(): array
{
return [
'name' => $this->name,
'data' => $this->data,
'timestamp' => $this->timestamp,
'tenantId' => $this->tenantId,
'identityId' => $this->identityId,
];
}
}
}
-124
View File
@@ -1,124 +0,0 @@
<?php
declare(strict_types=1);
namespace KTXF\Event;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;
final class EventDispatcher implements EventDispatcherInterface, DeferredEventProcessorInterface
{
/** @var array<string, list<Event>> */
private array $deferred = [];
private ?string $activeExecution = null;
private int $dispatchDepth = 0;
public function __construct(
private readonly EventListenerRegistry $registry,
private readonly ContainerInterface $container,
private readonly LoggerInterface $logger,
) {
}
public function dispatch(Event $event): void
{
if (++$this->dispatchDepth > 32) {
--$this->dispatchDepth;
throw new \RuntimeException('Event dispatch recursion limit exceeded.');
}
try {
$this->invoke($event, DeliveryMode::Immediate);
if ($this->registry->listeners($event->getName(), DeliveryMode::Deferred) !== []) {
if ($this->activeExecution === null) {
throw new \LogicException('Deferred events require an active execution scope.');
}
$this->deferred[$this->activeExecution][] = $event;
}
} finally {
--$this->dispatchDepth;
}
}
public function beginExecution(string $executionId): void
{
if ($this->activeExecution !== null) {
throw new \LogicException('An event execution scope is already active.');
}
$this->activeExecution = $executionId;
$this->deferred[$executionId] = [];
}
public function processDeferred(string $executionId): DeferredProcessingResult
{
if ($this->activeExecution !== $executionId) {
throw new \LogicException('Cannot process deferred events for an inactive execution.');
}
$processed = 0;
$deadline = microtime(true) + 1.0;
$deadlineExceeded = false;
$limitExceeded = false;
while (($event = array_shift($this->deferred[$executionId])) !== null) {
if ($processed >= 1000) {
$limitExceeded = true;
array_unshift($this->deferred[$executionId], $event);
break;
}
if (microtime(true) >= $deadline) {
$deadlineExceeded = true;
array_unshift($this->deferred[$executionId], $event);
break;
}
$processed += $this->invoke($event, DeliveryMode::Deferred);
}
$remaining = count($this->deferred[$executionId]);
unset($this->deferred[$executionId]);
$this->activeExecution = null;
return new DeferredProcessingResult(
$processed,
$remaining,
$deadlineExceeded,
$limitExceeded,
);
}
public function discardDeferred(string $executionId): void
{
unset($this->deferred[$executionId]);
if ($this->activeExecution === $executionId) {
$this->activeExecution = null;
}
}
private function invoke(Event $event, DeliveryMode $delivery): int
{
$processed = 0;
foreach ($this->registry->listeners($event->getName(), $delivery) as $listener) {
if ($event->isPropagationStopped()) {
break;
}
try {
$service = $this->container->get($listener->service);
$service->{$listener->method}($event);
$processed++;
} catch (\Throwable $error) {
$this->logger->error('Event listener failed.', [
'event' => $event->getName(),
'module' => $listener->module,
'listener' => $listener->service . '::' . $listener->method,
'exception' => $error,
]);
if ($listener->failurePolicy === FailurePolicy::Propagate) {
throw $error;
}
}
}
return $processed;
}
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace KTXF\Event;
interface EventListenerRegistrarInterface
{
/**
* @param class-string $service
*/
public function listen(
string $module,
string $event,
string $service,
string $method,
DeliveryMode $delivery = DeliveryMode::Immediate,
int $priority = 0,
FailurePolicy $failurePolicy = FailurePolicy::Continue,
): void;
}
-303
View File
@@ -1,303 +0,0 @@
<?php
declare(strict_types=1);
namespace KTXF\Event;
/**
* Security-specific event for authentication and access control events
*/
class SecurityEvent extends Event
{
// Event names
public const AUTH_SUCCESS = 'security.auth.success';
public const AUTH_FAILURE = 'security.auth.failure';
public const AUTH_LOGOUT = 'security.auth.logout';
public const TOKEN_REFRESH = 'security.token.refresh';
public const TOKEN_REVOKED = 'security.token.revoked';
public const ACCESS_DENIED = 'security.access.denied';
public const ACCESS_GRANTED = 'security.access.granted';
public const BRUTE_FORCE_DETECTED = 'security.brute_force.detected';
public const RATE_LIMIT_EXCEEDED = 'security.rate_limit.exceeded';
public const SUSPICIOUS_ACTIVITY = 'security.suspicious.activity';
public const IP_BLOCKED = 'security.ip.blocked';
public const IP_ALLOWED = 'security.ip.allowed';
public const DEVICE_BLOCKED = 'security.device.blocked';
private ?string $ipAddress = null;
private ?string $deviceFingerprint = null;
private ?string $userAgent = null;
private ?string $requestPath = null;
private ?string $requestMethod = null;
private ?string $userId = null;
private ?string $reason = null;
private int $severity = self::SEVERITY_INFO;
// Severity levels
public const SEVERITY_DEBUG = 0;
public const SEVERITY_INFO = 1;
public const SEVERITY_WARNING = 2;
public const SEVERITY_ERROR = 3;
public const SEVERITY_CRITICAL = 4;
/**
* Create a security event with common parameters
*/
public static function create(
string $name,
?string $ipAddress = null,
?string $deviceFingerprint = null,
array $data = []
): self {
$event = new self($name, $data);
$event->ipAddress = $ipAddress;
$event->deviceFingerprint = $deviceFingerprint;
// Set default severity based on event type
$event->severity = self::getSeverityForEvent($name);
return $event;
}
/**
* Create an authentication failure event
*/
public static function authFailure(
string $ipAddress,
?string $deviceFingerprint = null,
?string $userId = null,
?string $reason = null
): self {
$event = self::create(self::AUTH_FAILURE, $ipAddress, $deviceFingerprint, [
'userId' => $userId,
'reason' => $reason,
]);
$event->userId = $userId;
$event->reason = $reason;
return $event;
}
/**
* Create an authentication success event
*/
public static function authSuccess(
string $ipAddress,
?string $deviceFingerprint = null,
string $userId = null
): self {
$event = self::create(self::AUTH_SUCCESS, $ipAddress, $deviceFingerprint, [
'userId' => $userId,
]);
$event->userId = $userId;
return $event;
}
/**
* Create a brute force detection event
*/
public static function bruteForceDetected(
string $ipAddress,
int $failureCount,
int $windowSeconds
): self {
$event = self::create(self::BRUTE_FORCE_DETECTED, $ipAddress, null, [
'failureCount' => $failureCount,
'windowSeconds' => $windowSeconds,
]);
$event->reason = sprintf(
'%d failed attempts in %d seconds',
$failureCount,
$windowSeconds
);
return $event;
}
/**
* Create a rate limit exceeded event
*/
public static function rateLimitExceeded(
string $ipAddress,
int $requestCount,
int $windowSeconds,
?string $endpoint = null
): self {
$event = self::create(self::RATE_LIMIT_EXCEEDED, $ipAddress, null, [
'requestCount' => $requestCount,
'windowSeconds' => $windowSeconds,
'endpoint' => $endpoint,
]);
$event->requestPath = $endpoint;
$event->reason = sprintf(
'%d requests in %d seconds',
$requestCount,
$windowSeconds
);
return $event;
}
/**
* Create an access denied event
*/
public static function accessDenied(
string $ipAddress,
?string $deviceFingerprint = null,
?string $ruleId = null,
?string $reason = null
): self {
$event = self::create(self::ACCESS_DENIED, $ipAddress, $deviceFingerprint, [
'ruleId' => $ruleId,
'reason' => $reason,
]);
$event->reason = $reason;
return $event;
}
/**
* Get default severity for event types
*/
private static function getSeverityForEvent(string $eventName): int
{
return match ($eventName) {
self::AUTH_SUCCESS,
self::ACCESS_GRANTED,
self::TOKEN_REFRESH => self::SEVERITY_INFO,
self::AUTH_FAILURE,
self::ACCESS_DENIED,
self::AUTH_LOGOUT,
self::TOKEN_REVOKED => self::SEVERITY_WARNING,
self::RATE_LIMIT_EXCEEDED,
self::SUSPICIOUS_ACTIVITY => self::SEVERITY_ERROR,
self::BRUTE_FORCE_DETECTED,
self::IP_BLOCKED,
self::DEVICE_BLOCKED => self::SEVERITY_CRITICAL,
default => self::SEVERITY_INFO,
};
}
// Getters and setters
public function getIpAddress(): ?string
{
return $this->ipAddress;
}
public function setIpAddress(?string $ipAddress): self
{
$this->ipAddress = $ipAddress;
return $this;
}
public function getDeviceFingerprint(): ?string
{
return $this->deviceFingerprint;
}
public function setDeviceFingerprint(?string $deviceFingerprint): self
{
$this->deviceFingerprint = $deviceFingerprint;
return $this;
}
public function getUserAgent(): ?string
{
return $this->userAgent;
}
public function setUserAgent(?string $userAgent): self
{
$this->userAgent = $userAgent;
return $this;
}
public function getRequestPath(): ?string
{
return $this->requestPath;
}
public function setRequestPath(?string $requestPath): self
{
$this->requestPath = $requestPath;
return $this;
}
public function getRequestMethod(): ?string
{
return $this->requestMethod;
}
public function setRequestMethod(?string $requestMethod): self
{
$this->requestMethod = $requestMethod;
return $this;
}
public function getUserId(): ?string
{
return $this->userId;
}
public function setUserId(?string $userId): self
{
$this->userId = $userId;
return $this;
}
public function getReason(): ?string
{
return $this->reason;
}
public function setReason(?string $reason): self
{
$this->reason = $reason;
return $this;
}
public function getSeverity(): int
{
return $this->severity;
}
public function setSeverity(int $severity): self
{
$this->severity = $severity;
return $this;
}
public function getSeverityLabel(): string
{
return match ($this->severity) {
self::SEVERITY_DEBUG => 'DEBUG',
self::SEVERITY_INFO => 'INFO',
self::SEVERITY_WARNING => 'WARNING',
self::SEVERITY_ERROR => 'ERROR',
self::SEVERITY_CRITICAL => 'CRITICAL',
default => 'UNKNOWN',
};
}
/**
* Override toArray to include security-specific fields
*/
public function toArray(): array
{
return array_merge(parent::toArray(), [
'ipAddress' => $this->ipAddress,
'deviceFingerprint' => $this->deviceFingerprint,
'userAgent' => $this->userAgent,
'requestPath' => $this->requestPath,
'requestMethod' => $this->requestMethod,
'userId' => $this->userId,
'reason' => $this->reason,
'severity' => $this->severity,
'severityLabel' => $this->getSeverityLabel(),
]);
}
}
+2
View File
@@ -95,6 +95,7 @@ class IpUtils
if ($netmask < 0 || $netmask > 32) {
return self::setCacheResult($cacheKey, false);
}
$netmask = (int)$netmask;
} else {
$address = $ip;
$netmask = 32;
@@ -149,6 +150,7 @@ class IpUtils
if ($netmask < 1 || $netmask > 128) {
return self::setCacheResult($cacheKey, false);
}
$netmask = (int)$netmask;
} else {
if (!filter_var($ip, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6)) {
return self::setCacheResult($cacheKey, false);
@@ -11,6 +11,7 @@ namespace KTXF\Mail\Provider;
use KTXF\Mail\Service\ServiceBaseInterface;
use KTXF\Resource\Provider\ResourceProviderBaseInterface;
use KTXF\Resource\SystemIdentity;
/**
* Provider Base Interface
@@ -24,15 +25,9 @@ interface ProviderBaseInterface extends ResourceProviderBaseInterface{
public const JSON_TYPE = 'mail:provider';
/**
* Reserved user identifier for system-owned mail services
*
* Services stored under this user id belong to the tenant itself rather
* than any real user (e.g. accounts used to deliver system-generated
* messages such as verification codes and password resets).
*
* @since 2026.07.01
* @deprecated Use SystemIdentity::USER.
*/
public const USER_SYSTEM = 'system';
public const USER_SYSTEM = SystemIdentity::USER;
/**
* Finds a service that handles a specific email address
@@ -56,12 +56,19 @@ interface ServiceEntityMutableInterface {
/**
* Modifies an existing entity
*
* The returned entity's identifier is authoritative and may differ from
* the target identifier. Providers without in-place update support may
* implement this as an append-and-replace (or equivalent create-then-
* destroy) operation, in which case the target identifier is superseded
* and no longer resolvable; callers must persist the returned identifier
* rather than assume the target remains valid.
*
* @since 2025.05.01
*
* @param EntityIdentifier $target Target entity identifier
* @param MessagePropertiesMutableInterface $properties Entity properties to update
*
* @return EntityBaseInterface Modified entity
* @return EntityBaseInterface Modified entity, with its own authoritative identifier
*/
public function entityModify(EntityIdentifier $target, MessagePropertiesMutableInterface $properties): EntityBaseInterface;
+32
View File
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace KTXF\Preview;
use InvalidArgumentException;
final class MimeType
{
public static function normalize(string $mimeType): string
{
$mimeType = strtolower(trim(explode(';', $mimeType, 2)[0]));
if (preg_match('~^[a-z0-9!#$&^_.+-]+/[a-z0-9!#$&^_.+-]+$~', $mimeType) !== 1) {
throw new InvalidArgumentException("Invalid MIME type '{$mimeType}'");
}
return $mimeType;
}
public static function matches(string $pattern, string $mimeType): bool
{
$mimeType = self::normalize($mimeType);
$pattern = strtolower(trim($pattern));
if ($pattern === '*/*') {
return true;
}
if (preg_match('~^[a-z0-9!#$&^_.+-]+/\*$~', $pattern) === 1) {
return str_starts_with($mimeType, substr($pattern, 0, -1));
}
return self::normalize($pattern) === $mimeType;
}
}
@@ -0,0 +1,11 @@
<?php
declare(strict_types=1);
namespace KTXF\Preview;
use RuntimeException;
final class PreviewGenerationException extends RuntimeException
{
}
+32
View File
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace KTXF\Preview;
use InvalidArgumentException;
final readonly class PreviewRequest
{
public string $preferredMimeType;
public function __construct(
public int $maxWidth,
public int $maxHeight,
string $preferredMimeType,
public int $quality,
public int $maxSourceSize = 26214400,
) {
if ($this->maxWidth < 1 || $this->maxHeight < 1) {
throw new InvalidArgumentException('Preview dimensions must be positive');
}
if ($this->quality < 1 || $this->quality > 100) {
throw new InvalidArgumentException('Preview quality must be between 1 and 100');
}
if ($this->maxSourceSize < 1) {
throw new InvalidArgumentException('Preview maximum source size must be positive');
}
$this->preferredMimeType = MimeType::normalize($preferredMimeType);
}
}
+25
View File
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace KTXF\Preview;
use InvalidArgumentException;
use KTXF\Resource\BinaryResource;
final readonly class PreviewResult
{
public function __construct(
public BinaryResource $resource,
public ?int $width = null,
public ?int $height = null,
) {
MimeType::normalize($this->resource->mimeType());
if ($this->width !== null && $this->width < 1) {
throw new InvalidArgumentException('Preview result width must be positive');
}
if ($this->height !== null && $this->height < 1) {
throw new InvalidArgumentException('Preview result height must be positive');
}
}
}
+46
View File
@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace KTXF\Preview;
use Closure;
use InvalidArgumentException;
use KTXF\Resource\BinaryResource;
final readonly class PreviewSource
{
public string $mimeType;
/**
* @param Closure(): BinaryResource $resourceFactory
*/
public function __construct(
public string $sourceType,
public string $identity,
public string $signature,
string $mimeType,
public ?int $size,
public Closure $resourceFactory,
) {
if (preg_match('/^[a-z][a-z0-9-]*$/', $this->sourceType) !== 1) {
throw new InvalidArgumentException('Preview source type must use lowercase letters, numbers, and hyphens');
}
if ($this->identity === '' || $this->signature === '') {
throw new InvalidArgumentException('Preview sources require an identity and content signature');
}
if ($this->size !== null && $this->size < 0) {
throw new InvalidArgumentException('Preview source size cannot be negative');
}
$this->mimeType = MimeType::normalize($mimeType);
}
public function open(): BinaryResource
{
$resource = ($this->resourceFactory)();
if (!$resource instanceof BinaryResource) {
throw new PreviewGenerationException('Preview source factory did not return a BinaryResource');
}
return $resource;
}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace KTXF\Preview\Provider;
use KTXF\Preview\PreviewRequest;
use KTXF\Preview\PreviewResult;
use KTXF\Preview\PreviewSource;
use KTXF\Resource\Provider\ProviderInterface;
interface PreviewProviderInterface extends ProviderInterface
{
public function supports(string $sourceMimeType, PreviewRequest $request): bool;
public function generate(PreviewSource $source, PreviewRequest $request): PreviewResult;
public function priority(): int;
}
@@ -15,6 +15,8 @@ interface ProviderInterface
public const TYPE_PEOPLE = 'people';
public const TYPE_CHRONO = 'chrono';
public const TYPE_MAIL = 'mail';
public const TYPE_SYSTEM_STORE = 'system-store';
public const TYPE_PREVIEW = 'preview';
/**
* Provider type (e.g., 'authentication', 'document', 'people', 'chrono', 'mail')

Some files were not shown because too many files have changed in this diff Show More