Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions app/Services/Auth/ITwoFactorAuditService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php namespace App\Services\Auth;
/**
* Copyright 2026 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/

use Auth\User;

/**
* Interface ITwoFactorAuditService
* @package App\Services\Auth
*/
interface ITwoFactorAuditService
{
/**
* Persist a TwoFactorAuditLog record and emit corresponding OTLP attributes.
*
* @param User $user The user the event relates to.
* @param string $eventType One of the TwoFactorAuditLog::Event* constants.
* @param string $method One of the TwoFactorAuditLog::Method* constants.
* @param string $ipAddress Client IP address (IPv4 or IPv6).
* @param array|null $metadata Optional structured context; stored as JSON.
*
* @throws \InvalidArgumentException if $eventType or $method is not in the allowed set.
*/
public function log(User $user, string $eventType, string $method, string $ipAddress, ?array $metadata = null): void;
}
80 changes: 80 additions & 0 deletions app/Services/Auth/TwoFactorAuditService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<?php
namespace App\Services\Auth;
/**
* Copyright 2026 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/

use App\Jobs\EmitAuditLogJob;
use App\libs\Auth\Models\TwoFactorAuditLog;
use Auth\Repositories\ITwoFactorAuditLogRepository;
use Auth\User;
use Illuminate\Support\Facades\Log;

/**
* Class TwoFactorAuditService
* @package App\Services\Auth
*/
final class TwoFactorAuditService implements ITwoFactorAuditService
{
public function __construct(
private readonly ITwoFactorAuditLogRepository $repository
) {
}

/**
* @inheritDoc
*/
public function log(User $user, string $eventType, string $method, string $ipAddress, ?array $metadata = null): void
{
Log::debug('TwoFactorAuditService::log', [
'user_id' => $user->getId(),
'event_type' => $eventType,
'method' => $method,
'ip_address' => $ipAddress,
]);
Comment on lines +38 to +43
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Avoid logging raw user identifiers in debug audit traces.

Line 38 currently logs user_id and ip_address directly. That increases privacy/compliance risk in log storage without being required for core behavior. Prefer removing these fields or redacting/hashing them before logging.

Suggested minimal change
-        Log::debug('TwoFactorAuditService::log', [
-            'user_id' => $user->getId(),
-            'event_type' => $eventType,
-            'method' => $method,
-            'ip_address' => $ipAddress,
-        ]);
+        Log::debug('TwoFactorAuditService::log', [
+            'event_type' => $eventType,
+            'method' => $method,
+        ]);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
Log::debug('TwoFactorAuditService::log', [
'user_id' => $user->getId(),
'event_type' => $eventType,
'method' => $method,
'ip_address' => $ipAddress,
]);
Log::debug('TwoFactorAuditService::log', [
'event_type' => $eventType,
'method' => $method,
]);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@app/Services/Auth/TwoFactorAuditService.php` around lines 38 - 43, The
Log::debug call in TwoFactorAuditService::log currently emits raw 'user_id' and
'ip_address'; change it to avoid storing PII by removing those fields or
replacing them with a deterministic, non-reversible token (e.g., an HMAC/sha256
or other app-key-based hash) so you can still correlate events without exposing
raw identifiers; update the Log::debug invocation in the
TwoFactorAuditService::log method to keep 'event_type' and 'method' but
redact/hash 'user_id' and 'ip_address' (use the app key or a configured secret
to compute the hash).


$auditLog = new TwoFactorAuditLog();
$auditLog->setUser($user);
$auditLog->setEventType($eventType); // throws InvalidArgumentException on unknown type
$auditLog->setMethod($method); // throws InvalidArgumentException on unknown method
$auditLog->setIpAddress($ipAddress);
// user_agent is captured from the current HTTP request context; falls back to empty
// string in CLI / queue contexts. A future signature change may accept $userAgent
// explicitly if project conventions require it (see ticket CU-86ba2z5gz).
$auditLog->setUserAgent(request()?->userAgent() ?? '');
$auditLog->setMetadata($metadata);

$this->repository->add($auditLog, true);

if (config('opentelemetry.enabled', false)) {
EmitAuditLogJob::dispatch('two_factor.audit', [
'two_factor.event_type' => $eventType,
'two_factor.method' => $method,
'two_factor.user_id' => $user->getId(),
'two_factor.ip_address' => $ipAddress,
'two_factor.success' => $this->resolveSuccess($eventType),
'two_factor.device_trusted' => $eventType === TwoFactorAuditLog::EventDeviceTrusted,
'elasticsearch.index' => config('opentelemetry.logs.elasticsearch_index', 'logs-audit'),
]);
}
}

/**
* Derive whether the 2FA event represents a successful outcome.
* Only challenge_failed is treated as a failure; all other event types
* represent informational or successful operations.
*/
private function resolveSuccess(string $eventType): bool
{
return $eventType !== TwoFactorAuditLog::EventChallengeFailed;
}
}
2 changes: 2 additions & 0 deletions app/Services/Auth/TwoFactorServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,14 @@ public function boot(): void
public function register(): void
{
$this->app->singleton(IDeviceTrustService::class, DeviceTrustService::class);
$this->app->singleton(ITwoFactorAuditService::class, TwoFactorAuditService::class);
}

public function provides(): array
{
return [
IDeviceTrustService::class,
ITwoFactorAuditService::class,
];
}
}
1 change: 1 addition & 0 deletions phpunit.xml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
<file>./tests/Unit/MFA/AbstractMFAChallengeStrategyTest.php</file>
<file>./tests/Unit/MFA/EmailOTPMFAChallengeStrategyTest.php</file>
<file>./tests/Unit/MFA/MFAChallengeStrategyFactoryTest.php</file>
<file>./tests/Unit/TwoFactorAuditServiceTest.php</file>
</testsuite>
</testsuites>
<php>
Expand Down
227 changes: 227 additions & 0 deletions tests/Unit/TwoFactorAuditServiceTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,227 @@
<?php
namespace Tests\Unit;
/**
* Copyright 2026 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/

use App\Jobs\EmitAuditLogJob;
use App\libs\Auth\Models\TwoFactorAuditLog;
use App\Services\Auth\TwoFactorAuditService;
use Auth\Repositories\ITwoFactorAuditLogRepository;
use Auth\User;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Queue;
use Mockery;
use Tests\TestCase;

/**
* Class TwoFactorAuditServiceTest
* @package Tests\Unit
*/
final class TwoFactorAuditServiceTest extends TestCase
{
/** @var TwoFactorAuditService */
private TwoFactorAuditService $service;

/** @var \Mockery\MockInterface&ITwoFactorAuditLogRepository */
private $repository;

/** @var \Mockery\MockInterface&User */
private $user;

protected function setUp(): void
{
parent::setUp();
Queue::fake();

$this->repository = Mockery::mock(ITwoFactorAuditLogRepository::class);
$this->service = new TwoFactorAuditService($this->repository);

$this->user = Mockery::mock(User::class);
$this->user->shouldReceive('getId')->andReturn(42);
}

protected function tearDown(): void
{
Mockery::close();
parent::tearDown();
}

// -------------------------------------------------------------------------
// log() persists TwoFactorAuditLog with correct fields
// -------------------------------------------------------------------------

public function testLogPersistsTwoFactorAuditLogWithCorrectFields(): void
{
/** @var TwoFactorAuditLog|null $persisted */
$persisted = null;

$this->repository
->shouldReceive('add')
->once()
->withArgs(function (TwoFactorAuditLog $log, bool $sync) use (&$persisted) {
$persisted = $log;
return $sync === true;
});

$this->service->log(
$this->user,
TwoFactorAuditLog::EventChallengeSucceeded,
TwoFactorAuditLog::MethodEmailOtp,
'127.0.0.1',
['attempt' => 1]
);

$this->assertNotNull($persisted);
$this->assertSame($this->user, $persisted->getUser());
$this->assertSame(TwoFactorAuditLog::EventChallengeSucceeded, $persisted->getEventType());
$this->assertSame(TwoFactorAuditLog::MethodEmailOtp, $persisted->getMethod());
$this->assertSame('127.0.0.1', $persisted->getIpAddress());
$this->assertSame(['attempt' => 1], $persisted->getMetadata());
}

// -------------------------------------------------------------------------
// log() emits OTLP attributes
// -------------------------------------------------------------------------

public function testLogEmitsOtlpAttributes(): void
{
Config::set('opentelemetry.enabled', true);

$this->repository->shouldReceive('add')->once();

$this->service->log(
$this->user,
TwoFactorAuditLog::EventChallengeSucceeded,
TwoFactorAuditLog::MethodEmailOtp,
'10.0.0.1'
);

Queue::assertPushed(EmitAuditLogJob::class, function (EmitAuditLogJob $job) {
return $job->logMessage === 'two_factor.audit'
&& $job->auditData['two_factor.event_type'] === TwoFactorAuditLog::EventChallengeSucceeded
&& $job->auditData['two_factor.method'] === TwoFactorAuditLog::MethodEmailOtp
&& $job->auditData['two_factor.user_id'] === 42
&& $job->auditData['two_factor.ip_address'] === '10.0.0.1'
&& $job->auditData['two_factor.success'] === true
&& $job->auditData['two_factor.device_trusted'] === false;
});
}

// -------------------------------------------------------------------------
// log() emits two_factor.success = false for challenge_failed
// -------------------------------------------------------------------------

public function testLogEmitsSuccessFalseForChallengeFailed(): void
{
Config::set('opentelemetry.enabled', true);

$this->repository->shouldReceive('add')->once();

$this->service->log(
$this->user,
TwoFactorAuditLog::EventChallengeFailed,
TwoFactorAuditLog::MethodEmailOtp,
'10.0.0.1'
);

Queue::assertPushed(EmitAuditLogJob::class, function (EmitAuditLogJob $job) {
return $job->auditData['two_factor.event_type'] === TwoFactorAuditLog::EventChallengeFailed
&& $job->auditData['two_factor.success'] === false;
});
}

// -------------------------------------------------------------------------
// log() does NOT dispatch job when OTLP is disabled (default)
// -------------------------------------------------------------------------

public function testLogDoesNotDispatchJobWhenOtlpDisabled(): void
{
Config::set('opentelemetry.enabled', false);

$this->repository->shouldReceive('add')->once();

$this->service->log(
$this->user,
TwoFactorAuditLog::EventChallengeSucceeded,
TwoFactorAuditLog::MethodEmailOtp,
'127.0.0.1'
);

Queue::assertNotPushed(EmitAuditLogJob::class);
}

// -------------------------------------------------------------------------
// log() accepts null metadata
// -------------------------------------------------------------------------

public function testLogAcceptsNullMetadata(): void
{
/** @var TwoFactorAuditLog|null $persisted */
$persisted = null;

$this->repository
->shouldReceive('add')
->once()
->withArgs(function (TwoFactorAuditLog $log) use (&$persisted) {
$persisted = $log;
return true;
});

$this->service->log(
$this->user,
TwoFactorAuditLog::EventChallengeIssued,
TwoFactorAuditLog::MethodTotp,
'192.168.1.1',
null
);

$this->assertNotNull($persisted);
$this->assertNull($persisted->getMetadata());
}

// -------------------------------------------------------------------------
// invalid event type throws InvalidArgumentException
// -------------------------------------------------------------------------

public function testInvalidEventTypeThrowsInvalidArgumentException(): void
{
$this->expectException(\InvalidArgumentException::class);

$this->repository->shouldNotReceive('add');

$this->service->log(
$this->user,
'not_a_valid_event',
TwoFactorAuditLog::MethodEmailOtp,
'127.0.0.1'
);
}

// -------------------------------------------------------------------------
// invalid method throws InvalidArgumentException
// -------------------------------------------------------------------------

public function testInvalidMethodThrowsInvalidArgumentException(): void
{
$this->expectException(\InvalidArgumentException::class);

$this->repository->shouldNotReceive('add');

$this->service->log(
$this->user,
TwoFactorAuditLog::EventChallengeIssued,
'not_a_valid_method',
'127.0.0.1'
);
}
}
Loading