8 Commits

Author SHA1 Message Date
Sebastian b8c1bc72f4 chore(deps): update dependency vue-i18n to v11.4.8
Build Test / build (pull_request) Successful in 26s
JS Unit Tests / test (pull_request) Successful in 24s
PHP Integration Tests / Integration Tests (pull_request) Failing after 1m22s
PHP Unit Tests / test (pull_request) Successful in 1m5s
2026-08-06 03:02:00 +00: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
26 changed files with 687 additions and 451 deletions
@@ -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;
@@ -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
{
@@ -2,8 +2,12 @@
declare(strict_types=1);
namespace KTXF\Event;
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;
@@ -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 = [];
+5 -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;
@@ -410,6 +411,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';
+5 -4
View File
@@ -11,9 +11,10 @@ use KTXC\Service\SystemFirewallStatusService;
use KTXC\Service\TenantFirewallLogService;
use KTXC\Service\TenantFirewallRuleService;
use KTXC\Service\TenantFirewallStatusService;
use KTXC\Security\Event\AuthenticationFailedEvent;
use KTXC\Security\Event\SecurityEvent;
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;
@@ -26,7 +27,7 @@ use KTXF\Module\ModuleInstanceAbstract;
class Module extends ModuleInstanceAbstract implements ModuleConsoleInterface, ModuleBrowserInterface
{
public function __construct(
private readonly EventListenerRegistry $events,
private readonly EventListenerRegistrarInterface $events,
) {
}
@@ -34,7 +35,7 @@ class Module extends ModuleInstanceAbstract implements ModuleConsoleInterface, M
{
$this->events->listen(
'core',
SecurityEvent::AUTH_FAILURE,
AuthenticationFailedEvent::class,
FirewallService::class,
'handleAuthFailure',
priority: 100,
@@ -0,0 +1,69 @@
<?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 $ipAddress,
private readonly ?string $deviceFingerprint = null,
private readonly ?string $userId = null,
private readonly ?string $reason = null,
?string $tenantId = null,
?string $identityId = null,
private readonly ?string $userAgent = null,
private readonly ?string $requestPath = null,
private readonly ?string $requestMethod = null,
) {
parent::__construct(
self::class,
['userId' => $userId, 'reason' => $reason],
$tenantId,
$identityId,
);
}
public function getIpAddress(): string
{
return $this->ipAddress;
}
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(): int
{
return SecurityEvent::SEVERITY_WARNING;
}
}
+249
View File
@@ -0,0 +1,249 @@
<?php
declare(strict_types=1);
namespace KTXC\Security\Event;
use KTXF\Event\Event;
/**
* Security-specific event for authentication and access control events
*/
final class SecurityEvent extends Event implements SecurityEventInterface
{
// Event names
public const AUTH_SUCCESS = 'security.auth.success';
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';
public const FIREWALL_RULE_CREATED = 'security.firewall.rule.created';
public const FIREWALL_RULE_EXTENDED = 'security.firewall.rule.extended';
public const FIREWALL_RULE_ENABLED = 'security.firewall.rule.enabled';
public const FIREWALL_RULE_DISABLED = 'security.firewall.rule.disabled';
public const FIREWALL_RULE_REMOVED = 'security.firewall.rule.removed';
public const FIREWALL_SETTINGS_UPDATED = 'security.firewall.settings.updated';
// 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;
private readonly int $severity;
public function __construct(
string $name,
array $data = [],
?string $tenantId = null,
?string $identityId = null,
private readonly ?string $ipAddress = 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,
?int $severity = null,
) {
parent::__construct($name, $data, $tenantId, $identityId);
$this->severity = $severity ?? self::getSeverityForEvent($name);
}
/**
* Create a security event with common parameters
*/
public static function create(
string $name,
?string $ipAddress = null,
?string $deviceFingerprint = null,
array $data = [],
?string $tenantId = null,
?string $identityId = null,
?string $userAgent = null,
?string $requestPath = null,
?string $requestMethod = null,
?string $userId = null,
?string $reason = null,
?int $severity = null,
): self {
return new self(
$name,
$data,
$tenantId,
$identityId,
$ipAddress,
$deviceFingerprint,
$userAgent,
$requestPath,
$requestMethod,
$userId,
$reason,
$severity,
);
}
/**
* Create an authentication success event
*/
public static function authSuccess(
string $ipAddress,
?string $deviceFingerprint = null,
?string $userId = null,
?string $tenantId = null,
): self {
return self::create(
self::AUTH_SUCCESS,
$ipAddress,
$deviceFingerprint,
['userId' => $userId],
tenantId: $tenantId,
userId: $userId,
);
}
/**
* Create a brute force detection event
*/
public static function bruteForceDetected(
string $ipAddress,
int $failureCount,
int $windowSeconds,
?string $tenantId = null,
): self {
return self::create(
self::BRUTE_FORCE_DETECTED,
$ipAddress,
data: ['failureCount' => $failureCount, 'windowSeconds' => $windowSeconds],
tenantId: $tenantId,
reason: sprintf('%d failed attempts in %d seconds', $failureCount, $windowSeconds),
);
}
/**
* Create a rate limit exceeded event
*/
public static function rateLimitExceeded(
string $ipAddress,
int $requestCount,
int $windowSeconds,
?string $endpoint = null,
?string $tenantId = null,
): self {
return self::create(
self::RATE_LIMIT_EXCEEDED,
$ipAddress,
data: [
'requestCount' => $requestCount,
'windowSeconds' => $windowSeconds,
'endpoint' => $endpoint,
],
tenantId: $tenantId,
requestPath: $endpoint,
reason: sprintf('%d requests in %d seconds', $requestCount, $windowSeconds),
);
}
/**
* Create an access denied event
*/
public static function accessDenied(
string $ipAddress,
?string $deviceFingerprint = null,
?string $ruleId = null,
?string $ruleScope = null,
?string $reason = null,
?string $tenantId = null,
?string $identityId = null,
): self {
return self::create(
self::ACCESS_DENIED,
$ipAddress,
$deviceFingerprint,
['ruleId' => $ruleId, 'ruleScope' => $ruleScope, 'reason' => $reason],
$tenantId,
$identityId,
reason: $reason,
);
}
/**
* 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::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 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(): int
{
return $this->severity;
}
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace KTXC\Security\Event;
interface SecurityEventInterface
{
public function getName(): string;
public function get(string $key, mixed $default = null): mixed;
public function getData(): array;
public function getEventId(): string;
public function getTenantId(): ?string;
public function getIdentityId(): ?string;
public function getIpAddress(): ?string;
public function getDeviceFingerprint(): ?string;
public function getUserAgent(): ?string;
public function getRequestPath(): ?string;
public function getRequestMethod(): ?string;
public function getUserId(): ?string;
public function getReason(): ?string;
public function getSeverity(): int;
}
+32 -19
View File
@@ -7,7 +7,7 @@ namespace KTXC\Service;
use KTXC\Models\Firewall\FirewallRuleObject;
use KTXC\Stores\FirewallStore;
use KTXF\Event\EventDispatcherInterface;
use KTXF\Event\SecurityEvent;
use KTXC\Security\Event\SecurityEvent;
use KTXF\IpUtils;
final class FirewallRuleManager
@@ -254,8 +254,13 @@ final class FirewallRuleManager
$origin
);
$event = new SecurityEvent(SecurityEvent::DEVICE_BLOCKED, ['device' => $fingerprint, 'reason' => $reason]);
$event->setDeviceFingerprint($fingerprint)->setReason($reason)->setTenantId($scope->tenantId);
$event = new SecurityEvent(
SecurityEvent::DEVICE_BLOCKED,
['device' => $fingerprint, 'reason' => $reason],
tenantId: $scope->tenantId,
deviceFingerprint: $fingerprint,
reason: $reason,
);
$this->events->dispatch($event);
return $rule;
@@ -499,8 +504,13 @@ final class FirewallRuleManager
string $ipAddress,
?string $reason
): void {
$event = new SecurityEvent($name, ['ip' => $ipAddress, 'reason' => $reason]);
$event->setIpAddress($ipAddress)->setReason($reason)->setTenantId($scope->tenantId);
$event = new SecurityEvent(
$name,
['ip' => $ipAddress, 'reason' => $reason],
tenantId: $scope->tenantId,
ipAddress: $ipAddress,
reason: $reason,
);
$this->events->dispatch($event);
}
@@ -511,20 +521,23 @@ final class FirewallRuleManager
array $change = []
): void
{
$event = new SecurityEvent($name, [
'ruleId' => $rule->getId(),
'ruleScope' => $rule->getScope(),
'ruleType' => $rule->getType(),
'ruleAction' => $rule->getAction(),
'ruleValue' => $rule->getValue(),
'reason' => $rule->getReason(),
'origin' => $rule->getMetadata()['origin'] ?? self::ORIGIN_MANUAL,
'expiresAt' => $rule->getExpiresAt()?->format(\DateTimeInterface::ATOM),
...($rule->getMetadata() ?? []),
...$change,
]);
$event->setTenantId($rule->getTenantId())
->setIdentityId($actorId ?? $rule->getCreatedBy());
$event = new SecurityEvent(
$name,
[
'ruleId' => $rule->getId(),
'ruleScope' => $rule->getScope(),
'ruleType' => $rule->getType(),
'ruleAction' => $rule->getAction(),
'ruleValue' => $rule->getValue(),
'reason' => $rule->getReason(),
'origin' => $rule->getMetadata()['origin'] ?? self::ORIGIN_MANUAL,
'expiresAt' => $rule->getExpiresAt()?->format(\DateTimeInterface::ATOM),
...($rule->getMetadata() ?? []),
...$change,
],
tenantId: $rule->getTenantId(),
identityId: $actorId ?? $rule->getCreatedBy(),
);
$this->events->dispatch($event);
}
}
+16 -11
View File
@@ -9,8 +9,10 @@ use KTXC\Models\Firewall\FirewallRuleObject;
use KTXC\Models\Firewall\FirewallLogObject;
use KTXC\Stores\FirewallStore;
use KTXC\Context\TenantContextInterface;
use KTXC\Security\Event\AuthenticationFailedEvent;
use KTXC\Security\Event\SecurityEvent;
use KTXC\Security\Event\SecurityEventInterface;
use KTXF\Event\EventDispatcherInterface;
use KTXF\Event\SecurityEvent;
use KTXF\IpUtils;
/**
@@ -130,7 +132,7 @@ 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();
@@ -139,7 +141,6 @@ class FirewallService
return;
}
$event->setTenantId($tenantId);
$log = $this->securityLog($event);
if ($log === null || !$this->store->createLogOnce($log)) {
return;
@@ -195,8 +196,12 @@ class FirewallService
int $blockDuration
): void {
// Publish brute force event
$event = SecurityEvent::bruteForceDetected($ipAddress, $failureCount, $windowSeconds);
$event->setTenantId($tenantId);
$event = SecurityEvent::bruteForceDetected(
$ipAddress,
$failureCount,
$windowSeconds,
$tenantId,
);
$this->events->dispatch($event);
$this->rules->blockIp(
@@ -222,7 +227,7 @@ class FirewallService
/**
* Log security event to firewall logs
*/
public function logSecurityEvent(SecurityEvent $event): void
public function logSecurityEvent(SecurityEventInterface $event): void
{
$log = $this->securityLog($event);
if ($log !== null) {
@@ -230,7 +235,7 @@ class FirewallService
}
}
private function securityLog(SecurityEvent $event): ?FirewallLogObject
private function securityLog(SecurityEventInterface $event): ?FirewallLogObject
{
$tenantId = $event->getTenantId() ?? $this->tenantContext->identifier();
$ruleScope = $event->get('ruleScope');
@@ -261,7 +266,7 @@ class FirewallService
private function mapEventToLogType(string $eventName): string
{
return match ($eventName) {
SecurityEvent::AUTH_FAILURE => FirewallLogObject::EVENT_AUTH_FAILURE,
AuthenticationFailedEvent::class => 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,
@@ -280,7 +285,7 @@ class FirewallService
/**
* Map security event to result
*/
private function mapEventToResult(SecurityEvent $event): string
private function mapEventToResult(SecurityEventInterface $event): string
{
return match ($event->getName()) {
SecurityEvent::AUTH_SUCCESS,
@@ -308,9 +313,9 @@ class FirewallService
$deviceFingerprint,
$rule->getId(),
$rule->getScope(),
$rule->getReason()
$rule->getReason(),
$this->tenantContext->identifier(),
);
$event->setTenantId($this->tenantContext->identifier());
$this->events->dispatch($event);
}
+12 -8
View File
@@ -6,7 +6,7 @@ namespace KTXC\Service;
use KTXC\Models\Tenant\TenantConfiguration;
use KTXF\Event\EventDispatcherInterface;
use KTXF\Event\SecurityEvent;
use KTXC\Security\Event\SecurityEvent;
final class FirewallSettingsService
{
@@ -52,13 +52,17 @@ final class FirewallSettingsService
$tenant->setConfiguration($configuration);
$this->tenants->deposit($tenant);
$event = new SecurityEvent(SecurityEvent::FIREWALL_SETTINGS_UPDATED, [
'changeReason' => $reason,
'changeOrigin' => FirewallRuleManager::ORIGIN_MANUAL,
'previous' => $previous,
'current' => $current,
]);
$event->setTenantId($tenantId)->setIdentityId($actorId);
$event = new SecurityEvent(
SecurityEvent::FIREWALL_SETTINGS_UPDATED,
[
'changeReason' => $reason,
'changeOrigin' => FirewallRuleManager::ORIGIN_MANUAL,
'previous' => $previous,
'current' => $current,
],
tenantId: $tenantId,
identityId: $actorId,
);
$this->events->dispatch($event);
return $current;
+20 -44
View File
@@ -10,16 +10,18 @@ namespace KTXF\Event;
class Event
{
private bool $propagationStopped = false;
private array $data = [];
private float $timestamp;
private string $eventId;
private ?string $tenantId = null;
private ?string $identityId = null;
private readonly array $data;
private readonly float $timestamp;
private readonly string $eventId;
public function __construct(
private readonly string $name,
array $data = []
array $data = [],
private readonly ?string $tenantId = null,
private readonly ?string $identityId = null,
) {
self::validateData($data);
$this->data = $data;
$this->timestamp = microtime(true);
$this->eventId = bin2hex(random_bytes(16));
@@ -41,15 +43,6 @@ class Event
return $this->data[$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
*/
@@ -111,15 +104,6 @@ class Event
return $this->tenantId;
}
/**
* Set tenant ID for multi-tenant context
*/
public function setTenantId(?string $tenantId): self
{
$this->tenantId = $tenantId;
return $this;
}
/**
* Get identity ID (user who triggered the event)
*/
@@ -128,26 +112,18 @@ class Event
return $this->identityId;
}
/**
* Set identity ID
*/
public function setIdentityId(?string $identityId): self
private static function validateData(array $data): void
{
$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,
];
foreach ($data as $value) {
if (is_array($value)) {
self::validateData($value);
continue;
}
if ($value !== null && !is_scalar($value)) {
throw new \InvalidArgumentException(
'Event data must contain only scalar, null, or array values.',
);
}
}
}
}
@@ -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;
}
-311
View File
@@ -1,311 +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';
public const FIREWALL_RULE_CREATED = 'security.firewall.rule.created';
public const FIREWALL_RULE_EXTENDED = 'security.firewall.rule.extended';
public const FIREWALL_RULE_ENABLED = 'security.firewall.rule.enabled';
public const FIREWALL_RULE_DISABLED = 'security.firewall.rule.disabled';
public const FIREWALL_RULE_REMOVED = 'security.firewall.rule.removed';
public const FIREWALL_SETTINGS_UPDATED = 'security.firewall.settings.updated';
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 $ruleScope = null,
?string $reason = null
): self {
$event = self::create(self::ACCESS_DENIED, $ipAddress, $deviceFingerprint, [
'ruleId' => $ruleId,
'ruleScope' => $ruleScope,
'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(),
]);
}
}
+3 -3
View File
@@ -17,9 +17,9 @@ use KTXC\Service\TenantService;
use KTXF\Cache\BlobCacheInterface;
use KTXF\Cache\EphemeralCacheInterface;
use KTXF\Cache\PersistentCacheInterface;
use KTXF\Event\DeferredEventProcessorInterface;
use KTXF\Event\DeferredProcessingResult;
use KTXF\Event\EventListenerRegistry;
use KTXC\Event\DeferredEventProcessorInterface;
use KTXC\Event\DeferredProcessingResult;
use KTXC\Event\EventListenerRegistry;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\MockObject\MockObject;
@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace KTXT\Unit\Event;
use KTXC\Security\Event\AuthenticationFailedEvent;
use KTXC\Security\Event\SecurityEvent;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
final class AuthenticationFailedEventTest extends TestCase
{
#[Test]
#[TestDox('Authentication failure state is typed and complete at construction')]
public function constructsTypedState(): void
{
$event = new AuthenticationFailedEvent(
'203.0.113.10',
'device-a',
'user-a',
'Invalid credentials',
'tenant-a',
'identity-a',
'Test Agent',
'/login',
'POST',
);
self::assertSame(AuthenticationFailedEvent::class, $event->getName());
self::assertSame('203.0.113.10', $event->getIpAddress());
self::assertSame('device-a', $event->getDeviceFingerprint());
self::assertSame('user-a', $event->getUserId());
self::assertSame('Invalid credentials', $event->getReason());
self::assertSame('tenant-a', $event->getTenantId());
self::assertSame('identity-a', $event->getIdentityId());
self::assertSame('Test Agent', $event->getUserAgent());
self::assertSame('/login', $event->getRequestPath());
self::assertSame('POST', $event->getRequestMethod());
self::assertSame(SecurityEvent::SEVERITY_WARNING, $event->getSeverity());
}
}
+2 -2
View File
@@ -6,8 +6,8 @@ namespace KTXT\Unit\Event;
use KTXF\Event\DeliveryMode;
use KTXF\Event\Event;
use KTXF\Event\EventDispatcher;
use KTXF\Event\EventListenerRegistry;
use KTXC\Event\EventDispatcher;
use KTXC\Event\EventListenerRegistry;
use KTXF\Event\FailurePolicy;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\Attributes\Test;
+41
View File
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace KTXT\Unit\Event;
use KTXF\Event\Event;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
final class EventTest extends TestCase
{
#[Test]
#[TestDox('Event data and context are supplied during construction')]
public function constructsCompleteEventState(): void
{
$event = new Event(
'test.event',
['nested' => ['value' => 'original']],
'tenant-a',
'identity-a',
);
$copy = $event->getData();
$copy['nested']['value'] = 'changed';
self::assertSame('original', $event->get('nested')['value']);
self::assertSame('tenant-a', $event->getTenantId());
self::assertSame('identity-a', $event->getIdentityId());
}
#[Test]
#[TestDox('Event data rejects mutable object references')]
public function rejectsMutablePayloadValues(): void
{
$this->expectException(\InvalidArgumentException::class);
new Event('test.event', ['mutable' => new \stdClass()]);
}
}
@@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
namespace KTXT\Unit\Event;
use KTXC\Security\Event\SecurityEvent;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
final class SecurityEventTest extends TestCase
{
#[Test]
#[TestDox('Direct construction applies the event type default severity')]
public function appliesDefaultSeverityDuringConstruction(): void
{
self::assertSame(
SecurityEvent::SEVERITY_WARNING,
(new SecurityEvent(SecurityEvent::AUTH_LOGOUT))->getSeverity(),
);
self::assertSame(
SecurityEvent::SEVERITY_ERROR,
(new SecurityEvent(SecurityEvent::RATE_LIMIT_EXCEEDED))->getSeverity(),
);
self::assertSame(
SecurityEvent::SEVERITY_CRITICAL,
(new SecurityEvent(SecurityEvent::DEVICE_BLOCKED))->getSeverity(),
);
self::assertSame(
SecurityEvent::SEVERITY_INFO,
(new SecurityEvent(SecurityEvent::FIREWALL_RULE_CREATED))->getSeverity(),
);
}
#[Test]
#[TestDox('Construction can override the event type default severity')]
public function allowsSeverityOverride(): void
{
$event = new SecurityEvent(
SecurityEvent::AUTH_LOGOUT,
severity: SecurityEvent::SEVERITY_CRITICAL,
);
self::assertSame(SecurityEvent::SEVERITY_CRITICAL, $event->getSeverity());
}
#[Test]
#[TestDox('Event state exposes no mutation methods')]
public function exposesNoMutationMethods(): void
{
foreach ([
'set',
'setTenantId',
'setIdentityId',
'setIpAddress',
'setDeviceFingerprint',
'setUserAgent',
'setRequestPath',
'setRequestMethod',
'setUserId',
'setReason',
'setSeverity',
] as $method) {
self::assertFalse(method_exists(SecurityEvent::class, $method));
}
}
}
+5 -4
View File
@@ -15,9 +15,10 @@ use KTXC\Service\TenantFirewallLogService;
use KTXC\Service\TenantFirewallStatusService;
use KTXC\Service\SystemFirewallStatusService;
use KTXC\Service\TenantFirewallRuleService;
use KTXC\Event\EventListenerRegistry;
use KTXC\Security\Event\AuthenticationFailedEvent;
use KTXC\Security\Event\SecurityEvent;
use KTXF\Event\DeliveryMode;
use KTXF\Event\EventListenerRegistry;
use KTXF\Event\SecurityEvent;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
@@ -38,9 +39,9 @@ final class CoreModuleTest extends TestCase
self::assertSame(['core'], array_values(array_unique(array_column($definitions, 'module'))));
self::assertSame(
FirewallService::class,
$registry->listeners(SecurityEvent::AUTH_FAILURE, DeliveryMode::Immediate)[0]->service,
$registry->listeners(AuthenticationFailedEvent::class, DeliveryMode::Immediate)[0]->service,
);
self::assertSame([], $registry->listeners(SecurityEvent::AUTH_FAILURE, DeliveryMode::Deferred));
self::assertSame([], $registry->listeners(AuthenticationFailedEvent::class, DeliveryMode::Deferred));
foreach ([
SecurityEvent::RATE_LIMIT_EXCEEDED,
SecurityEvent::SUSPICIOUS_ACTIVITY,
@@ -11,7 +11,7 @@ use KTXC\Service\FirewallRuleManager;
use KTXC\Service\FirewallRuleScope;
use KTXC\Stores\FirewallStore;
use KTXF\Event\EventDispatcherInterface;
use KTXF\Event\SecurityEvent;
use KTXC\Security\Event\SecurityEvent;
use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\MockObject\MockObject;
+41 -33
View File
@@ -8,6 +8,7 @@ use KTXC\Context\TenantContextInterface;
use KTXC\Models\Firewall\FirewallRuleObject;
use KTXC\Models\Firewall\FirewallLogObject;
use KTXC\Models\Tenant\TenantConfiguration;
use KTXC\Security\Event\AuthenticationFailedEvent;
use KTXC\Service\FirewallService;
use KTXC\Service\FirewallRuleCache;
use KTXC\Service\FirewallRuleManager;
@@ -210,14 +211,14 @@ class FirewallServiceTest extends TestCase
&& $log->getEventType() === FirewallLogObject::EVENT_RULE_MATCH;
}))
->willReturnArgument(0);
$event = \KTXF\Event\SecurityEvent::accessDenied(
$event = \KTXC\Security\Event\SecurityEvent::accessDenied(
'203.0.113.10',
null,
'tenant-rule',
FirewallRuleObject::SCOPE_TENANT,
'Tenant block'
'Tenant block',
'tenant-a',
);
$event->setTenantId('tenant-a');
$this->service->logSecurityEvent($event);
}
@@ -234,7 +235,7 @@ class FirewallServiceTest extends TestCase
&& $log->getRuleScope() === FirewallRuleObject::SCOPE_SYSTEM;
}))
->willReturnArgument(0);
$event = \KTXF\Event\SecurityEvent::accessDenied(
$event = \KTXC\Security\Event\SecurityEvent::accessDenied(
'203.0.113.10',
null,
'system-rule',
@@ -252,7 +253,7 @@ class FirewallServiceTest extends TestCase
$this->store->expects($this->never())->method('createLog');
$this->service->logSecurityEvent(
\KTXF\Event\SecurityEvent::authFailure('203.0.113.10')
new AuthenticationFailedEvent('203.0.113.10')
);
}
@@ -271,13 +272,13 @@ class FirewallServiceTest extends TestCase
&& $metadata['windowSeconds'] === 60;
}))
->willReturnArgument(0);
$event = \KTXF\Event\SecurityEvent::rateLimitExceeded(
$event = \KTXC\Security\Event\SecurityEvent::rateLimitExceeded(
'203.0.113.10',
101,
60,
'/login'
'/login',
'tenant-a',
);
$event->setTenantId('tenant-a');
$this->service->logSecurityEvent($event);
}
@@ -296,15 +297,15 @@ class FirewallServiceTest extends TestCase
&& $log->getMetadata()['detector'] === 'payload-signature';
}))
->willReturnArgument(0);
$event = \KTXF\Event\SecurityEvent::create(
\KTXF\Event\SecurityEvent::SUSPICIOUS_ACTIVITY,
$event = \KTXC\Security\Event\SecurityEvent::create(
\KTXC\Security\Event\SecurityEvent::SUSPICIOUS_ACTIVITY,
'203.0.113.20',
null,
['detector' => 'payload-signature']
['detector' => 'payload-signature'],
tenantId: 'tenant-a',
requestPath: '/admin',
requestMethod: 'POST',
);
$event->setTenantId('tenant-a')
->setRequestPath('/admin')
->setRequestMethod('POST');
$this->service->logSecurityEvent($event);
}
@@ -323,15 +324,15 @@ class FirewallServiceTest extends TestCase
&& $log->getIdentityId() === 'operator';
}))
->willReturnArgument(0);
$event = new \KTXF\Event\SecurityEvent(
\KTXF\Event\SecurityEvent::FIREWALL_RULE_DISABLED,
$event = new \KTXC\Security\Event\SecurityEvent(
\KTXC\Security\Event\SecurityEvent::FIREWALL_RULE_DISABLED,
[
'ruleId' => 'rule-123',
'ruleScope' => FirewallRuleObject::SCOPE_SYSTEM,
'origin' => FirewallRuleManager::ORIGIN_MANUAL,
]
],
identityId: 'operator',
);
$event->setIdentityId('operator');
$this->service->logSecurityEvent($event);
}
@@ -349,11 +350,12 @@ class FirewallServiceTest extends TestCase
&& $log->getMetadata()['changeReason'] === 'Tighten controls'
))
->willReturnArgument(0);
$event = new \KTXF\Event\SecurityEvent(
\KTXF\Event\SecurityEvent::FIREWALL_SETTINGS_UPDATED,
['changeReason' => 'Tighten controls']
$event = new \KTXC\Security\Event\SecurityEvent(
\KTXC\Security\Event\SecurityEvent::FIREWALL_SETTINGS_UPDATED,
['changeReason' => 'Tighten controls'],
tenantId: 'tenant-a',
identityId: 'operator',
);
$event->setTenantId('tenant-a')->setIdentityId('operator');
$this->service->logSecurityEvent($event);
}
@@ -376,8 +378,10 @@ class FirewallServiceTest extends TestCase
->willReturn(4);
$this->events->expects($this->never())->method('dispatch');
$event = \KTXF\Event\SecurityEvent::authFailure('203.0.113.10');
$event->setTenantId('tenant-a');
$event = new AuthenticationFailedEvent(
'203.0.113.10',
tenantId: 'tenant-a',
);
$this->service->handleAuthFailure($event);
self::assertSame(8, $this->currentConfiguration->firewall()->maxAuthFailures());
@@ -400,8 +404,10 @@ class FirewallServiceTest extends TestCase
->with('tenant-a', '203.0.113.10', 300)
->willReturn(0);
$event = \KTXF\Event\SecurityEvent::authFailure('203.0.113.10');
$event->setTenantId('tenant-a');
$event = new AuthenticationFailedEvent(
'203.0.113.10',
tenantId: 'tenant-a',
);
$this->service->handleAuthFailure($event);
}
@@ -449,13 +455,15 @@ class FirewallServiceTest extends TestCase
&$lifecycleOrigin
): void {
$publishedTenants[] = $event->getTenantId();
if ($event->getName() === \KTXF\Event\SecurityEvent::FIREWALL_RULE_CREATED) {
if ($event->getName() === \KTXC\Security\Event\SecurityEvent::FIREWALL_RULE_CREATED) {
$lifecycleOrigin = $event->get('origin');
}
});
$event = \KTXF\Event\SecurityEvent::authFailure('203.0.113.10');
$event->setTenantId('tenant-event');
$event = new AuthenticationFailedEvent(
'203.0.113.10',
tenantId: 'tenant-event',
);
$this->service->handleAuthFailure($event);
self::assertSame(['tenant-event', 'tenant-event', 'tenant-event'], $publishedTenants);
@@ -478,7 +486,7 @@ class FirewallServiceTest extends TestCase
$this->events->expects($this->never())->method('dispatch');
$this->service->handleAuthFailure(
\KTXF\Event\SecurityEvent::authFailure('203.0.113.10')
new AuthenticationFailedEvent('203.0.113.10')
);
}
@@ -492,7 +500,7 @@ class FirewallServiceTest extends TestCase
->willReturn(0);
$this->service->handleAuthFailure(
\KTXF\Event\SecurityEvent::authFailure('203.0.113.10')
new AuthenticationFailedEvent('203.0.113.10')
);
}
@@ -504,7 +512,7 @@ class FirewallServiceTest extends TestCase
$this->store->expects($this->never())->method('depositRule');
$this->service->handleAuthFailure(
\KTXF\Event\SecurityEvent::authFailure('203.0.113.10')
new AuthenticationFailedEvent('203.0.113.10')
);
}
@@ -518,7 +526,7 @@ class FirewallServiceTest extends TestCase
->method('countRecentFailures')
->with('tenant-a', '203.0.113.10', 300)
->willReturn(1);
$event = \KTXF\Event\SecurityEvent::authFailure('203.0.113.10');
$event = new AuthenticationFailedEvent('203.0.113.10');
$eventId = $event->getEventId();
$this->service->handleAuthFailure($event);
@@ -9,7 +9,7 @@ use KTXC\Models\Tenant\TenantObject;
use KTXC\Service\FirewallSettingsService;
use KTXC\Service\TenantService;
use KTXF\Event\EventDispatcherInterface;
use KTXF\Event\SecurityEvent;
use KTXC\Security\Event\SecurityEvent;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;