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
133 changes: 133 additions & 0 deletions app/Audit/AbstractAuditLogFormatter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
<?php

namespace App\Audit;

use App\Audit\Utils\DateFormatter;

/**
* Copyright 2025 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.
**/

abstract class AbstractAuditLogFormatter implements IAuditLogFormatter
{
protected ?AuditContext $ctx = null;
protected string $event_type;

public function __construct(string $event_type)
{
$this->event_type = $event_type;
}

final public function setContext(AuditContext $ctx): void
{
$this->ctx = $ctx;
}

protected function getUserInfo(): string
{
if (app()->runningInConsole()) {
return 'Worker Job';
}
if (!$this->ctx) {
return 'Unknown (unknown)';
}

$user_name = 'Unknown';
if ($this->ctx->userFirstName || $this->ctx->userLastName) {
$user_name = trim(sprintf("%s %s", $this->ctx->userFirstName ?? '', $this->ctx->userLastName ?? '')) ?: 'Unknown';
} elseif ($this->ctx->userEmail) {
$user_name = $this->ctx->userEmail;
}

$user_id = $this->ctx->userId ?? 'unknown';
return sprintf("%s (%s)", $user_name, $user_id);
}

protected function formatAuditDate($date, string $format = 'Y-m-d H:i:s'): string
{
return DateFormatter::format($date, $format);
}

protected function getIgnoredFields(): array
{
return [
'last_created',
'last_updated',
'last_edited',
'created_by',
'updated_by'
];
}

protected function formatChangeValue($value): string
{
if (is_bool($value)) {
return $value ? 'true' : 'false';
}
if (is_null($value)) {
return 'null';
}
if ($value instanceof \DateTimeInterface) {
return $value->format('Y-m-d H:i:s');
}
if ($value instanceof \Doctrine\Common\Collections\Collection) {
$count = $value->count();
return sprintf('Collection[%d items]', $count);
}
if (is_object($value)) {
$className = get_class($value);
return sprintf('%s', $className);
}
if (is_array($value)) {
return sprintf('Array[%d items]', count($value));
}
return (string) $value;
}


protected function buildChangeDetails(array $change_set): string
{
$changed_fields = [];
$ignored_fields = $this->getIgnoredFields();

foreach ($change_set as $prop_name => $change_values) {
if (in_array($prop_name, $ignored_fields)) {
continue;
}

$old_value = $change_values[0] ?? null;
$new_value = $change_values[1] ?? null;

$formatted_change = $this->formatFieldChange($prop_name, $old_value, $new_value);
if ($formatted_change !== null) {
$changed_fields[] = $formatted_change;
}
}

if (empty($changed_fields)) {
return 'properties without changes registered';
}

$fields_summary = count($changed_fields) . ' field(s) modified: ';
return $fields_summary . implode(' | ', $changed_fields);
}

protected function formatFieldChange(string $prop_name, $old_value, $new_value): ?string
{
$old_display = $this->formatChangeValue($old_value);
$new_display = $this->formatChangeValue($new_value);

return sprintf("Property \"%s\" has changed from \"%s\" to \"%s\"", $prop_name, $old_display, $new_display);
}

abstract public function format(mixed $subject, array $change_set): ?string;
}
31 changes: 31 additions & 0 deletions app/Audit/AuditContext.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php
namespace App\Audit;
/**
* Copyright 2025 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.
**/
class AuditContext
{
public function __construct(
public ?int $userId = null,
public ?string $userEmail = null,
public ?string $userFirstName = null,
public ?string $userLastName = null,
public ?string $uiApp = null,
public ?string $uiFlow = null,
public ?string $route = null,
public ?string $rawRoute = null,
public ?string $httpMethod = null,
public ?string $clientIp = null,
public ?string $userAgent = null,
) {
}
}
133 changes: 133 additions & 0 deletions app/Audit/AuditEventListener.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
<?php
namespace App\Audit;
/**
* Copyright 2025 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\Audit\Interfaces\IAuditStrategy;
use Auth\Repositories\IUserRepository;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Route;
use Illuminate\Http\Request;
use OAuth2\IResourceServerContext;
/**
* Class AuditEventListener
* @package App\Audit
*/
class AuditEventListener
{
private const ROUTE_METHOD_SEPARATOR = '|';

public function onFlush(OnFlushEventArgs $eventArgs): void
{
if (app()->environment('testing')) {
return;
}
$em = $eventArgs->getObjectManager();
$uow = $em->getUnitOfWork();
// Strategy selection based on environment configuration
$strategy = $this->getAuditStrategy($em);
if (!$strategy) {
return; // No audit strategy enabled
}

$ctx = $this->buildAuditContext();

try {
foreach ($uow->getScheduledEntityInsertions() as $entity) {
$strategy->audit($entity, [], IAuditStrategy::EVENT_ENTITY_CREATION, $ctx);
}

foreach ($uow->getScheduledEntityUpdates() as $entity) {
$strategy->audit($entity, $uow->getEntityChangeSet($entity), IAuditStrategy::EVENT_ENTITY_UPDATE, $ctx);
}

foreach ($uow->getScheduledEntityDeletions() as $entity) {
$strategy->audit($entity, [], IAuditStrategy::EVENT_ENTITY_DELETION, $ctx);
}

foreach ($uow->getScheduledCollectionUpdates() as $col) {
$strategy->audit($col, [], IAuditStrategy::EVENT_COLLECTION_UPDATE, $ctx);
}
} catch (\Exception $e) {
Log::error('Audit event listener failed', [
'error' => $e->getMessage(),
'strategy_class' => get_class($strategy),
'trace' => $e->getTraceAsString(),
]);
}
}

/**
* Get the appropriate audit strategy based on environment configuration
*/
private function getAuditStrategy($em): ?IAuditStrategy
{
// Check if OTLP audit is enabled
if (config('opentelemetry.enabled', false)) {
try {
Log::debug("AuditEventListener::getAuditStrategy strategy AuditLogOtlpStrategy");
return App::make(AuditLogOtlpStrategy::class);
} catch (\Exception $e) {
Log::warning('Failed to create OTLP audit strategy, falling back to database', [
'error' => $e->getMessage()
]);
}
}

// Use database strategy (either as default or fallback)
Log::debug("AuditEventListener::getAuditStrategy strategy AuditLogStrategy");
return new AuditLogStrategy($em);
}

private function buildAuditContext(): AuditContext
{
$resourceCtx = app(IResourceServerContext::class);
$userId = $resourceCtx->getCurrentUserId();
$user = null;
if ($userId) {
$userRepo = app(IUserRepository::class);
$user = $userRepo->getById($userId);
}

$uiContext = []; // app()->bound('ui.context') ? app('ui.context') : [];

$req = request();
$rawRoute = null;
// does not resolve the route when app is running in console mode
if ($req instanceof Request && !app()->runningInConsole()) {
try {
$route = Route::getRoutes()->match($req);
$method = $route->methods[0] ?? 'UNKNOWN';
$rawRoute = $method . self::ROUTE_METHOD_SEPARATOR . $route->uri;
} catch (\Exception $e) {
Log::warning($e);
}
}

return new AuditContext(
userId: $user?->getId(),
userEmail: $user?->getEmail(),
userFirstName: $user?->getFirstName(),
userLastName: $user?->getLastName(),
uiApp: $uiContext['app'] ?? null,
uiFlow: $uiContext['flow'] ?? null,
route: $req?->path(),
httpMethod: $req?->method(),
clientIp: $req?->ip(),
userAgent: $req?->userAgent(),
rawRoute: $rawRoute
);
}
}
Loading
Loading