-
Notifications
You must be signed in to change notification settings - Fork 0
Feature | Add Doctrine logging generic classes #96
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
matiasperrone-exo
wants to merge
16
commits into
main
Choose a base branch
from
feat/add-doctrine-event-listener
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+2,359
−5
Open
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
9239342
feat: add Doctrine logging generic classes
matiasperrone 1eea5ad
chore: remove reflection from class name detection
matiasperrone 04d37fb
chore: remove summit models
matiasperrone d164d91
chore: add config file audit_log
matiasperrone 989ddbd
chore: revert lint fix to main version
matiasperrone 2a6949e
chore: add listener in doctrine config
matiasperrone 680c18b
fix: Change interface and attribute on user search
matiasperrone 8576299
fix: Add OTEL config AuditProvider
matiasperrone b1806bd
fix: rollback to "main" identation on config/app.php
matiasperrone 6cac23f
chore: Change variables names from $member[...] to $user
matiasperrone ba31489
chore: use getId instead field
matiasperrone e6deb12
chore: implement the same changes as summit-api
matiasperrone 20dfadf
chore: Add PR's changes requested
matiasperrone 6831fe5
chore: Add Unit Tests
matiasperrone b1ae8a4
chore: Add unit test suit for Formatters
matiasperrone e92e0ef
chore: separate SDK OTEL test suite from custom formatters
matiasperrone File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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, | ||
| ) { | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| ); | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.