A free open source IT asset/license management system
Fixed #19985 - return correct status code, added new LDAP log
sniped3fd939a2c8c
diff --git a/app/Console/Commands/LdapSync.php b/app/Console/Commands/LdapSync.phpindex 24a4a66ee2..cdfe725432 100644--- a/app/Console/Commands/LdapSync.php+++ b/app/Console/Commands/LdapSync.php@@ -81,6 +81,8 @@ class LdapSync extends Commandreturn 1;}+ Log::channel('ldap')->info('LDAP sync started by ' . $this->describeInitiator() . '.');+try {// Tag every action_log written during this run (direct writes// and the observer-driven writes User saves trigger) as `ldap`@@ -92,8 +94,40 @@ class LdapSync extends Command}}- private function runSync()+ /**+ * Human-readable description of who kicked off this sync, for the+ * ldap-channel startup line.+ */+ private function describeInitiator(): string{+ if (auth()->check()) {+ $user = auth()->user();+ $via = request()->is('api/*') ? 'API' : 'GUI';++ return 'user ' . $user->username . ' (ID ' . $user->id . ') via ' . $via;+ }++ $script = $_SERVER['argv'][1] ?? '';+ if (in_array($script, ['schedule:run', 'schedule:work', 'schedule:test'], true)) {+ return 'the Laravel scheduler or user-initiated CLI';+ }++ $osUser = function_exists('posix_geteuid')+ ? (posix_getpwuid(posix_geteuid())['name'] ?? null)+ : null;+ $osUser = $osUser ?: (get_current_user() ?: 'unknown');++ return 'CLI as OS user ' . $osUser;+ }++ /**+ * Returns an int exit code so the Artisan runner surfaces the+ * right status to a cron / systemd caller.+ */+ private function runSync(): int+ {+ $startedAt = microtime(true);+ini_set('max_execution_time', config('app.ldap_time_limit')); // 600 seconds = 10 minutesini_set('memory_limit', config('app.ldap_memory_limit'));@@ -115,9 +149,9 @@ class LdapSync extends Command$json_summary = ['error' => true, 'error_message' => $e->getMessage(), 'summary' => []];$this->info(json_encode($json_summary));}- Log::info($e);+ Log::channel('ldap')->info($e);- return [];+ return self::FAILURE;}$summary = [];@@ -133,7 +167,7 @@ class LdapSync extends Commandforeach ($this->option('location_id') as $location_id) {$location_ou = Location::where('id', '=', $location_id)->value('ldap_ou');$search_base = $location_ou;- Log::debug('Importing users from specified location OU: \"'.$search_base.'\".');+ Log::channel('ldap')->debug('Importing users from specified location OU: \"' . $search_base . '\".');}}@@ -143,7 +177,7 @@ class LdapSync extends Command*/if ($this->option('base_dn') != '') {$search_base = $this->option('base_dn');- Log::debug('Importing users from specified base DN: \"'.$search_base.'\".');+ Log::channel('ldap')->debug('Importing users from specified base DN: \"' . $search_base . '\".');}/**@@ -175,31 +209,31 @@ class LdapSync extends Command$json_summary = ['error' => true, 'error_message' => $e->getMessage(), 'summary' => []];$this->info(json_encode($json_summary));}- Log::info($e);+ Log::channel('ldap')->info($e);- return [];+ return self::FAILURE;}/* Determine which location to assign users to by default. */$default_location = null;if ($this->option('location') != '') {if ($default_location = Location::where('name', '=', $this->option('location'))->first()) {- Log::debug('Location name '.$this->option('location').' passed');- Log::debug('Importing to '.$default_location->name.' ('.$default_location->id.')');+ Log::channel('ldap')->debug('Location name ' . $this->option('location') . ' passed');+ Log::channel('ldap')->debug('Importing to ' . $default_location->name . ' (' . $default_location->id . ')');}} elseif ($this->option('location_id')) {// TODO - figure out how or why this is an array?foreach ($this->option('location_id') as $location_id) {if ($default_location = Location::where('id', '=', $location_id)->first()) {- Log::debug('Location ID '.$location_id.' passed');- Log::debug('Importing to '.$default_location->name.' ('.$default_location->id.')');+ Log::channel('ldap')->debug('Location ID ' . $location_id . ' passed');+ Log::channel('ldap')->debug('Importing to ' . $default_location->name . ' (' . $default_location->id . ')');}}}if (! isset($default_location)) {- Log::debug('That location is invalid or a location was not provided, so no location will be assigned by default.');+ Log::channel('ldap')->debug('That location is invalid or a location was not provided, so no location will be assigned by default.');}/* Process locations with explicitly defined OUs, if doing a full import. */@@ -215,7 +249,7 @@ class LdapSync extends Commandarray_multisort($ldap_ou_lengths, SORT_ASC, $ldap_ou_locations);if (count($ldap_ou_locations) > 0) {- Log::debug('Some locations have special OUs set. Locations will be automatically set for users in those OUs.');+ Log::channel('ldap')->debug('Some locations have special OUs set. Locations will be automatically set for users in those OUs.');}// Inject location information fields@@ -233,9 +267,9 @@ class LdapSync extends Command$json_summary = ['error' => true, 'error_message' => trans('admin/users/message.error.ldap_could_not_search').' Location: '.$ldap_loc['name'].' (ID: '.$ldap_loc['id'].') cannot connect to "'.$ldap_loc['ldap_ou'].'" - '.$e->getMessage(), 'summary' => []];$this->info(json_encode($json_summary));}- Log::info($e);+ Log::channel('ldap')->info($e);- return [];+ return self::FAILURE;}$usernames = [];for ($i = 0; $i < $location_users['count']; $i++) {@@ -322,7 +356,7 @@ class LdapSync extends Commandtry {$ldap_manager = Ldap::findLdapUsers($item['manager'], -1, $this->option('filter'));} catch (\Exception $e) {- Log::warning('Manager lookup caused an exception: '.$e->getMessage().'. Falling back to direct username lookup');+ Log::channel('ldap')->warning('Manager lookup caused an exception: ' . $e->getMessage() . '. Falling back to direct username lookup');// Hail-mary for Okta manager 'shortnames' - will only work if// Okta configuration is using full email-address-style usernames$ldap_manager = [@@ -348,7 +382,7 @@ class LdapSync extends Command}} catch (\Exception $e) {$add_manager_to_cache = false;- \Log::warning('Handling ldap manager '.$item['manager'].' caused an exception: '.$e->getMessage().'. Continuing synchronization.');+ \Log::channel('ldap')->warning('Handling ldap manager ' . $item['manager'] . ' caused an exception: ' . $e->getMessage() . '. Continuing synchronization.');}}if ($add_manager_to_cache) {@@ -527,9 +561,16 @@ class LdapSync extends Command} elseif ($this->option('json_summary')) {$json_summary = ['error' => false, 'error_message' => '', 'summary' => $summary]; // hardcoding the error to false and the error_message to blank seems a bit weird$this->info(json_encode($json_summary));- } else {- return $summary;}++ $elapsed = number_format(microtime(true) - $startedAt, 3);+ $successCount = count(array_filter($summary, fn($row) => ($row['status'] ?? '') === 'success'));+ Log::channel('ldap')->info(+ 'LDAP sync completed in ' . $elapsed . 's. '+ . count($summary) . ' users processed (' . $successCount . ' success).',+ );++ return self::SUCCESS;}/**diff --git a/app/Models/Ldap.php b/app/Models/Ldap.phpindex 18758973f6..8fdb8f71ba 100644--- a/app/Models/Ldap.php+++ b/app/Models/Ldap.php@@ -149,7 +149,7 @@ class Ldap extends Modelif (! $userDn) {throw new Exception('No user DN found');}- \Log::debug("FOUND DN IS: $userDn");+ \Log::channel('ldap')->debug("FOUND DN IS: $userDn");// The temptation now is to do ldap_unbind on the $admin_conn, but that gets handled in the 'finally' below.// I don't know if that means a separate 'connection' is maintained to the LDAP server or not, and would// definitely prefer to not do that if we can avoid it. But I don't know enough about the LDAP protocol to@@ -164,7 +164,7 @@ class Ldap extends Modelreturn array_change_key_case($user);} catch (Exception $e) {- \Log::debug('Exception on fast find-and-bind: '.$e->getMessage());+ \Log::channel('ldap')->debug('Exception on fast find-and-bind: '.$e->getMessage());if ($slow_failure) {sleep($slow_failure);}@@ -218,22 +218,22 @@ class Ldap extends Model$filter = Setting::getSettings()->ldap_filter; // FIXME - this *does* respect the ldap filter, but I believe that AdLdap2 did *not*.$filterQuery = "({$filter}({$filterQuery}))";- Log::debug('Filter query: '.$filterQuery);+ Log::channel('ldap')->debug('Filter query: '.$filterQuery);// only try this if we have an Admin username set; otherwise use the 'legacy' methodif (($settings->ldap_uname) && ($baseDn)) {// in the fallowing call, we pick a slow-failure of 0 because we might need to fall through to 'legacy'$fast_bind = self::findAndBindMultiOU($baseDn, $filterQuery, $password, 0);if ($fast_bind) {- \Log::debug('Fast bind worked');+ \Log::channel('ldap')->debug('Fast bind worked');return $fast_bind;}- \Log::debug('Fast bind failed; falling through to legacy bind');+ \Log::channel('ldap')->debug('Fast bind failed; falling through to legacy bind');}if (! $ldapbind = @ldap_bind($connection, $userDn, $password)) {- Log::debug("Status of binding user: $userDn to directory: (directly!) ".($ldapbind ? 'success' : 'FAILURE'));+ Log::channel('ldap')->debug("Status of binding user: $userDn to directory: (directly!) ".($ldapbind ? 'success' : 'FAILURE'));// replicate the old bad-decryption-key detection behavior heretry {Crypt::decrypt(Setting::getSettings()->ldap_pword);@@ -273,8 +273,8 @@ class Ldap extends Modelpublic static function shouldUseSaslExternal(object $config): bool{return self::saslExternalAvailable()- && !empty($config->ldap_client_tls_cert)- && !empty($config->ldap_client_tls_key)+ && ! empty($config->ldap_client_tls_cert)+ && ! empty($config->ldap_client_tls_key)&& empty($config->ldap_uname)&& empty($config->ldap_pword);}@@ -586,7 +586,7 @@ class Ldap extends Model$user->notes = 'Imported on first login from LDAP';if (! $user->save()) {- Log::debug('Could not create user.'.$user->getErrors());+ Log::channel('ldap')->debug('Could not create user.'.$user->getErrors());throw new Exception('Could not create user: '.$user->getErrors());}@@ -649,7 +649,7 @@ class Ldap extends Model$ldap_controls = [['oid' => LDAP_CONTROL_PAGEDRESULTS, 'iscritical' => false, 'value' => ['size' => $count == -1 || $count > $page_size ? $page_size : $count, 'cookie' => $cookie]]];// }$search_results = ldap_search($ldapconn, $base_dn, $filter, $attributes, 0, /* $page_size */ -1, -1, LDAP_DEREF_NEVER, $ldap_controls); // TODO - I hate the @, and I hate that we get a full page even if we ask for 10 records. Can we use an ldap_control?- Log::debug('LDAP search executed successfully.');+ Log::channel('ldap')->debug('LDAP search executed successfully.');if (! $search_results) {return redirect()->route('users.index')->with('error', trans('admin/users/message.error.ldap_could_not_search').ldap_error($ldapconn)); // TODO this is never called in any routed context - only from the Artisan command. So this redirect will never work.}@@ -663,9 +663,9 @@ class Ldap extends Modelif (isset($controls[LDAP_CONTROL_PAGEDRESULTS]['value']['cookie'])) {// You need to pass the cookie from the last call to the next one$cookie = $controls[LDAP_CONTROL_PAGEDRESULTS]['value']['cookie'];- Log::debug('okay, at least one more page to go!!!');+ Log::channel('ldap')->debug('okay, at least one more page to go!!!');} else {- Log::debug("okay, we're out of pages - no cookie (or empty cookie) was passed");+ Log::channel('ldap')->debug("okay, we're out of pages - no cookie (or empty cookie) was passed");$cookie = '';}// Empty cookie means last page@@ -679,7 +679,7 @@ class Ldap extends Model// Add results to result set$global_count += $results['count'];$result_set = array_merge($result_set, $results);- Log::debug("Total count is: $global_count");+ Log::channel('ldap')->debug("Total count is: $global_count");} while ($cookie !== null && $cookie != '' && ($count == -1 || $global_count < $count)); // some servers don't even have pagination, and some will give you more results than you asked for, so just see if you have enough.diff --git a/config/logging.php b/config/logging.phpindex 0fd670efb5..fb1ecd9312 100644--- a/config/logging.php+++ b/config/logging.php@@ -119,20 +119,20 @@ $config = ['days' => 30,],- // Sync-adapter log. SYNC_ADAPTERS_LOG_PATH lets the test env- // route writes to /dev/null via phpunit.xml so sync-adapter- // writes during tests don't pile up in the developer's real- // logs/sync-adapters.log file. Still uses the single driver- // so Monolog TestHandler capture (used by diagnostic endpoints- // + per-run download) still works - swapping to the null- // driver would short-circuit the handler stack and defeat- // our in-request log captures.+ // Sync-adapter log'sync-adapters' => ['driver' => 'single','path' => env('SYNC_ADAPTERS_LOG_PATH', storage_path('logs/sync-adapters.log')),'level' => env('LOG_LEVEL', 'info'),],+ // Dedicated LDAP log+ 'ldap' => [+ 'driver' => 'single',+ 'path' => env('LDAP_LOG_PATH', storage_path('logs/ldap.log')),+ 'level' => env('LOG_LEVEL', 'debug'),+ ],+'rollbar' => ['driver' => 'monolog','handler' => MonologHandler::class,diff --git a/phpunit.xml b/phpunit.xmlindex b4d1bca560..7ab2983422 100644--- a/phpunit.xml+++ b/phpunit.xml@@ -26,6 +26,7 @@<env name="QUEUE_CONNECTION" value="sync"/><env name="SESSION_DRIVER" value="array"/><env name="SYNC_ADAPTERS_LOG_PATH" value="/dev/null"/>+ <env name="LDAP_LOG_PATH" value="/dev/null"/><ini name="display_errors" value="true"/></php><source>diff --git a/tests/Feature/Users/LdapSyncMutexTest.php b/tests/Feature/Users/LdapSyncMutexTest.phpindex 2e03da9518..954ab3a9f7 100644--- a/tests/Feature/Users/LdapSyncMutexTest.php+++ b/tests/Feature/Users/LdapSyncMutexTest.php@@ -8,7 +8,6 @@ use Illuminate\Support\Facades\Artisan;use Illuminate\Support\Facades\Cache;use Tests\TestCase;-class LdapSyncMutexTest extends TestCase{protected function setUp(): void@@ -73,4 +72,16 @@ class LdapSyncMutexTest extends TestCase->assertOk()->assertViewHas('ldapSyncRunning', false);}++ public function test_bind_failure_returns_failure_exit_code(): void+ {+ $this->settings->set([+ 'ldap_enabled' => '1',+ 'ldap_server' => '',+ ]);++ $exitCode = Artisan::call('snipeit:ldap-sync');++ $this->assertSame(1, $exitCode, 'A bind-side failure must bubble up as exit code 1 rather than coerce to 0.');+ }}