refactor(security): add typed suspicious-activity event

Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
This commit is contained in:
2026-08-05 23:38:59 -04:00
parent 688afbe5a1
commit f4df769b3c
8 changed files with 176 additions and 16 deletions
+2 -1
View File
@@ -15,6 +15,7 @@ use KTXC\Security\Event\AccessDeniedEvent;
use KTXC\Security\Event\AuthenticationFailedEvent;
use KTXC\Security\Event\BruteForceDetectedEvent;
use KTXC\Security\Event\RateLimitExceededEvent;
use KTXC\Security\Event\SuspiciousActivityEvent;
use KTXC\Security\Event\SecurityEvent;
use KTXF\Event\DeliveryMode;
use KTXF\Event\EventListenerRegistrarInterface;
@@ -50,7 +51,7 @@ class Module extends ModuleInstanceAbstract implements ModuleConsoleInterface, M
AccessDeniedEvent::class,
BruteForceDetectedEvent::class,
RateLimitExceededEvent::class,
SecurityEvent::SUSPICIOUS_ACTIVITY,
SuspiciousActivityEvent::class,
SecurityEvent::FIREWALL_RULE_CREATED,
SecurityEvent::FIREWALL_RULE_EXTENDED,
SecurityEvent::FIREWALL_RULE_ENABLED,
@@ -19,8 +19,6 @@ final class SecurityEvent extends Event implements SecurityRequestEventInterface
public const ACCESS_GRANTED = 'security.access.granted';
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';
@@ -124,8 +122,6 @@ final class SecurityEvent extends Event implements SecurityRequestEventInterface
self::AUTH_LOGOUT,
self::TOKEN_REVOKED => self::SEVERITY_WARNING,
self::SUSPICIOUS_ACTIVITY => self::SEVERITY_ERROR,
self::IP_BLOCKED,
self::DEVICE_BLOCKED => self::SEVERITY_CRITICAL,
@@ -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(): int
{
return SecurityEvent::SEVERITY_ERROR;
}
}
+2 -1
View File
@@ -14,6 +14,7 @@ use KTXC\Security\Event\AccessDeniedEvent;
use KTXC\Security\Event\AuthenticationFailedEvent;
use KTXC\Security\Event\BruteForceDetectedEvent;
use KTXC\Security\Event\RateLimitExceededEvent;
use KTXC\Security\Event\SuspiciousActivityEvent;
use KTXC\Security\Event\SecurityEvent;
use KTXC\Security\Event\SecurityEventInterface;
use KTXC\Security\Event\SecurityRequestEventInterface;
@@ -286,7 +287,7 @@ class FirewallService
BruteForceDetectedEvent::class => FirewallLogObject::EVENT_BRUTE_FORCE,
RateLimitExceededEvent::class => FirewallLogObject::EVENT_RATE_LIMIT,
AccessDeniedEvent::class => FirewallLogObject::EVENT_RULE_MATCH,
SecurityEvent::SUSPICIOUS_ACTIVITY => FirewallLogObject::EVENT_SUSPICIOUS,
SuspiciousActivityEvent::class => FirewallLogObject::EVENT_SUSPICIOUS,
SecurityEvent::FIREWALL_RULE_CREATED => FirewallLogObject::EVENT_RULE_CREATED,
SecurityEvent::FIREWALL_RULE_EXTENDED => FirewallLogObject::EVENT_RULE_EXTENDED,
SecurityEvent::FIREWALL_RULE_ENABLED => FirewallLogObject::EVENT_RULE_ENABLED,
@@ -19,10 +19,6 @@ final class SecurityEventTest extends TestCase
SecurityEvent::SEVERITY_WARNING,
(new SecurityEvent(SecurityEvent::AUTH_LOGOUT))->getSeverity(),
);
self::assertSame(
SecurityEvent::SEVERITY_ERROR,
(new SecurityEvent(SecurityEvent::SUSPICIOUS_ACTIVITY))->getSeverity(),
);
self::assertSame(
SecurityEvent::SEVERITY_CRITICAL,
(new SecurityEvent(SecurityEvent::DEVICE_BLOCKED))->getSeverity(),
@@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
namespace KTXT\Unit\Event;
use KTXC\Security\Event\SecurityEvent;
use KTXC\Security\Event\SuspiciousActivityEvent;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
final class SuspiciousActivityEventTest extends TestCase
{
#[Test]
#[TestDox('Suspicious-activity state is typed and complete at construction')]
public function constructsTypedState(): void
{
$event = new SuspiciousActivityEvent(
ipAddress: '203.0.113.20',
detector: 'payload-signature',
detectionData: ['score' => 98],
tenantId: 'tenant-a',
identityId: 'identity-a',
deviceFingerprint: 'device-a',
userAgent: 'Test Agent',
requestPath: '/admin',
requestMethod: 'POST',
userId: 'user-a',
reason: 'Matched a blocked payload signature',
);
self::assertSame(SuspiciousActivityEvent::class, $event->getName());
self::assertSame('203.0.113.20', $event->getIpAddress());
self::assertSame('payload-signature', $event->getDetector());
self::assertSame(['score' => 98], $event->getDetectionData());
self::assertSame(['detector' => 'payload-signature', 'score' => 98], $event->getData());
self::assertSame('tenant-a', $event->getTenantId());
self::assertSame('identity-a', $event->getIdentityId());
self::assertSame('device-a', $event->getDeviceFingerprint());
self::assertSame('Test Agent', $event->getUserAgent());
self::assertSame('/admin', $event->getRequestPath());
self::assertSame('POST', $event->getRequestMethod());
self::assertSame('user-a', $event->getUserId());
self::assertSame('Matched a blocked payload signature', $event->getReason());
self::assertSame(SecurityEvent::SEVERITY_ERROR, $event->getSeverity());
}
#[Test]
#[TestDox('Suspicious activity rejects incomplete or conflicting detection context')]
public function rejectsInvalidDetectionContext(): void
{
foreach ([
['', 'payload-signature', []],
['203.0.113.20', '', []],
['203.0.113.20', 'payload-signature', ['detector' => 'replacement']],
] as $arguments) {
try {
new SuspiciousActivityEvent(...$arguments);
self::fail('Invalid suspicious-activity context was accepted.');
} catch (\InvalidArgumentException) {
$this->addToAssertionCount(1);
}
}
}
}
+2 -1
View File
@@ -20,6 +20,7 @@ use KTXC\Security\Event\AccessDeniedEvent;
use KTXC\Security\Event\AuthenticationFailedEvent;
use KTXC\Security\Event\BruteForceDetectedEvent;
use KTXC\Security\Event\RateLimitExceededEvent;
use KTXC\Security\Event\SuspiciousActivityEvent;
use KTXC\Security\Event\SecurityEvent;
use KTXF\Event\DeliveryMode;
use PHPUnit\Framework\Attributes\Test;
@@ -49,7 +50,7 @@ final class CoreModuleTest extends TestCase
AccessDeniedEvent::class,
BruteForceDetectedEvent::class,
RateLimitExceededEvent::class,
SecurityEvent::SUSPICIOUS_ACTIVITY,
SuspiciousActivityEvent::class,
SecurityEvent::FIREWALL_RULE_CREATED,
SecurityEvent::FIREWALL_RULE_EXTENDED,
SecurityEvent::FIREWALL_RULE_DISABLED,
@@ -14,6 +14,7 @@ use KTXC\Security\Event\AccessDeniedEvent;
use KTXC\Security\Event\AuthenticationFailedEvent;
use KTXC\Security\Event\BruteForceDetectedEvent;
use KTXC\Security\Event\RateLimitExceededEvent;
use KTXC\Security\Event\SuspiciousActivityEvent;
use KTXC\Service\FirewallService;
use KTXC\Service\FirewallRuleCache;
use KTXC\Service\FirewallRuleManager;
@@ -320,11 +321,9 @@ class FirewallServiceTest extends TestCase
&& $log->getMetadata()['detector'] === 'payload-signature';
}))
->willReturnArgument(0);
$event = \KTXC\Security\Event\SecurityEvent::create(
\KTXC\Security\Event\SecurityEvent::SUSPICIOUS_ACTIVITY,
'203.0.113.20',
null,
['detector' => 'payload-signature'],
$event = new SuspiciousActivityEvent(
ipAddress: '203.0.113.20',
detector: 'payload-signature',
tenantId: 'tenant-a',
requestPath: '/admin',
requestMethod: 'POST',