A free open source IT asset/license management system
Added action_source override for ldap and sync adapters
snipe0ebc88dba6d8
diff --git a/app/Console/Commands/LdapSync.php b/app/Console/Commands/LdapSync.phpindex b0ea6d43d1..27286450ab 100644--- a/app/Console/Commands/LdapSync.php+++ b/app/Console/Commands/LdapSync.php@@ -2,6 +2,7 @@namespace App\Console\Commands;+use App\Models\Actionlog;use App\Models\Asset;use App\Models\Group;use App\Models\Ldap;@@ -51,6 +52,21 @@ class LdapSync extends Commandexit();}+ // Tag every action_log written during this run (direct writes+ // and the observer-driven writes User saves trigger) as `ldap`+ // so the activity report distinguishes LDAP-created entries+ // from gui / api / sync-adapter origins.+ $previousActionSource = Actionlog::setAmbientSource('ldap');++ try {+ return $this->runSync();+ } finally {+ Actionlog::setAmbientSource($previousActionSource);+ }+ }++ private function runSync()+ {ini_set('max_execution_time', config('app.ldap_time_limit')); // 600 seconds = 10 minutesini_set('memory_limit', config('app.ldap_memory_limit'));diff --git a/app/Console/Commands/PullInventory.php b/app/Console/Commands/PullInventory.phpindex 91c3af66ea..532f163357 100644--- a/app/Console/Commands/PullInventory.php+++ b/app/Console/Commands/PullInventory.php@@ -2,6 +2,7 @@namespace App\Console\Commands;+use App\Models\Actionlog;use App\Models\SyncAdapterInstance;use App\SyncAdapters\SyncAdapter;use Illuminate\Console\Command;@@ -116,24 +117,26 @@ class PullInventory extends CommandLog::channel('sync-adapters')->info("{$slug} sync starting (CLI)");try {- foreach ($adapter->pull() as $record) {- try {- $result = SyncAdapter::syncFromRecord($record);- if ($result === null) {- $skipped++;- } else {- $seen++;+ Actionlog::withActionSource('sync:'.$slug, function () use ($adapter, $slug, &$seen, &$skipped, &$errors) {+ foreach ($adapter->pull() as $record) {+ try {+ $result = SyncAdapter::syncFromRecord($record);+ if ($result === null) {+ $skipped++;+ } else {+ $seen++;+ }+ } catch (Throwable $e) {+ $errors++;+ $sourceId = $record->sourceId;+ $message = $e->getMessage();+ // A single bad record shouldn't take down the run.+ // Log the offending host and keep going.+ $this->warn("Failed to sync host {$sourceId}: {$message}");+ Log::channel('sync-adapters')->warning("{$slug} sync: failed to upsert host {$sourceId}: {$message}");}- } catch (Throwable $e) {- $errors++;- $sourceId = $record->sourceId;- $message = $e->getMessage();- // A single bad record shouldn't take down the run.- // Log the offending host and keep going.- $this->warn("Failed to sync host {$sourceId}: {$message}");- Log::channel('sync-adapters')->warning("{$slug} sync: failed to upsert host {$sourceId}: {$message}");}- }+ });} catch (Throwable $e) {$message = $e->getMessage();$abortSummary = "Sync aborted: {$message}";diff --git a/app/Http/Controllers/Assets/AssetsController.php b/app/Http/Controllers/Assets/AssetsController.phpindex 168ad3b46a..7705fa84ff 100755--- a/app/Http/Controllers/Assets/AssetsController.php+++ b/app/Http/Controllers/Assets/AssetsController.php@@ -694,7 +694,14 @@ class AssetsController extends ControllerStorage::disk('public')->put($qr_key, $barcode_obj->getPngData());}- return Storage::disk('public')->response($qr_key, basename($qr_key), ['Content-type' => 'image/png']);+ // Buffered rather than StreamedResponse so S3 serving+ // works consistently. QR PNGs are a few KB, memory is+ // fine, and the streaming path was truncating bodies+ // on S3 somewhere in the StreamedResponse/readStream+ // pipeline.+ return response(Storage::disk('public')->get($qr_key), 200, [+ 'Content-type' => 'image/png',+ ]);}}@@ -745,7 +752,11 @@ class AssetsController extends Controller}}- return Storage::disk('public')->response($barcode_key, basename($barcode_key), ['Content-type' => 'image/png']);+ // Buffered rather than StreamedResponse so S3 serving+ // works consistently. See getQrCode() for context.+ return response(Storage::disk('public')->get($barcode_key), 200, [+ 'Content-type' => 'image/png',+ ]);}}diff --git a/app/Http/Controllers/SettingsController.php b/app/Http/Controllers/SettingsController.phpindex 7d73b64f5f..137e01ca26 100644--- a/app/Http/Controllers/SettingsController.php+++ b/app/Http/Controllers/SettingsController.php@@ -16,6 +16,7 @@ use App\Models\Actionlog;use App\Models\Asset;use App\Models\CustomField;use App\Models\Group;+use App\Models\Labels\CustomUserLabel;use App\Models\Setting;use App\Models\User;use App\Notifications\MailTest;@@ -37,7 +38,6 @@ use League\Csv\EscapeFormula;use Symfony\Component\HttpFoundation\BinaryFileResponse;use Symfony\Component\HttpFoundation\StreamedResponse;use ZipArchive;-use App\Models\Labels\CustomUserLabel;/*** This controller handles all actions related to Settings for@@ -603,7 +603,7 @@ class SettingsController extends Controller$setting = Setting::getSettings();if (str_starts_with($setting->label2_template, 'custom:')) {- $customLabelId = (int)str_replace('custom:', '', $setting->label2_template);+ $customLabelId = (int) str_replace('custom:', '', $setting->label2_template);$setting->label2_template_name = CustomUserLabel::find($customLabelId)?->name?? $setting->label2_template;@@ -700,7 +700,7 @@ class SettingsController extends ControllerCustomUserLabel::where('is_default', true)->update(['is_default' => false]);if (str_starts_with($selectedTemplate, 'custom:')) {- $customLabelId = (int)str_replace('custom:', '', $selectedTemplate);+ $customLabelId = (int) str_replace('custom:', '', $selectedTemplate);CustomUserLabel::whereKey($customLabelId)->update(['is_default' => true,@@ -1126,24 +1126,21 @@ class SettingsController extends ControllerLog::channel('sync-adapters')->info("{$instance->slug} sync starting (UI)");try {- foreach ($adapter->pull() as $record) {- try {- $result = \App\SyncAdapters\SyncAdapter::syncFromRecord($record);- if ($result === null) {- $skipped++;- } else {- $seen++;+ Actionlog::withActionSource('sync:'.$instance->slug, function () use ($adapter, $instance, &$seen, &$skipped, &$errors) {+ foreach ($adapter->pull() as $record) {+ try {+ $result = \App\SyncAdapters\SyncAdapter::syncFromRecord($record);+ if ($result === null) {+ $skipped++;+ } else {+ $seen++;+ }+ } catch (\Throwable $e) {+ $errors++;+ Log::channel('sync-adapters')->warning($instance->slug.' sync: failed to upsert host '.$record->sourceId.': '.$e->getMessage());}- } catch (\Throwable $e) {- $errors++;- Log::channel('sync-adapters')->warning(sprintf(- '%s sync: failed to upsert host %s: %s',- $instance->slug,- $record->sourceId,- $e->getMessage(),- ));}- }+ });} catch (\Throwable $e) {// Log the full exception server-side so admins can dig into// response bodies, stack traces, etc. via the dedicated@@ -1153,7 +1150,7 @@ class SettingsController extends Controller// message on 4xx/5xx, and internal error pages regularly// contain sensitive info we don't want to bounce into the// admin's browser.- Log::channel('sync-adapters')->warning(sprintf('%s sync aborted: %s', $instance->slug, $e->getMessage()), [+ Log::channel('sync-adapters')->warning($instance->slug.' sync aborted: '.$e->getMessage(), ['exception' => $e,]);diff --git a/app/Models/Actionlog.php b/app/Models/Actionlog.phpindex 9ac00f0489..0b511d4949 100755--- a/app/Models/Actionlog.php+++ b/app/Models/Actionlog.php@@ -32,6 +32,19 @@ class Actionlog extends SnipeModel// This is to manually set the source (via setActionSource()) for determineActionSource()protected ?string $source = null;+ /**+ * Ambient action-source for every action_log written inside a+ * long-running operation (LDAP sync, sync-adapter pulls) that has+ * no HTTP context to infer `gui` / `api` from and that spawns many+ * observer-driven writes we can't reach into individually.+ *+ * Set + restored around a callback via withActionSource(). The+ * priority order in determineActionSource() is: explicit per-log+ * $this->source first, ambient second, then the request-shape+ * fallbacks.+ */+ protected static ?string $ambientSource = null;+protected $with = ['adminuser'];protected $presenter = ActionlogPresenter::class;@@ -626,13 +639,39 @@ class Actionlog extends SnipeModel** @since v6.3.0*/+ /**+ * Run $callback with every action_log it writes stamped as $source.+ * Previous ambient value is restored on exit (including on+ * exception) so nested wraps don't leak out of their scope. Used by+ * LdapSync + the sync-adapter pull entry points to attribute+ * observer-driven writes to the owning operation.+ */+ public static function withActionSource(string $source, callable $callback): mixed+ {+ $previous = self::$ambientSource;+ self::$ambientSource = $source;+ try {+ return $callback();+ } finally {+ self::$ambientSource = $previous;+ }+ }+public function determineActionSource(): string{- // This is a manually set source+ // Explicit per-log override, set via setActionSource() on the+ // Actionlog instance before save.if ($this->source) {return $this->source;}+ // Ambient source set by a surrounding withActionSource() wrap.+ // Catches observer-driven writes from LDAP sync and sync-adapter+ // pulls that we can't reach to tag individually.+ if (self::$ambientSource !== null) {+ return self::$ambientSource;+ }+// This is an API callif (((request()->header('content-type') && (request()->header('accept')) == 'application/json'))&& (starts_with(request()->header('authorization'), 'Bearer '))