foreman_rh_cloud 15.0.0 → 15.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. checksums.yaml +4 -4
  2. data/app/controllers/api/v2/advisor_engine/advisor_engine_controller.rb +1 -73
  3. data/app/controllers/foreman_inventory_upload/accounts_controller.rb +29 -14
  4. data/app/controllers/insights_cloud/ui_requests_controller.rb +19 -2
  5. data/app/services/foreman_rh_cloud/insights_api_forwarder.rb +93 -79
  6. data/config/package-lock.json.plugin +7160 -21310
  7. data/config/routes.rb +0 -4
  8. data/lib/foreman_inventory_upload/async/generate_host_report.rb +6 -1
  9. data/lib/foreman_inventory_upload/async/host_inventory_report_job.rb +10 -0
  10. data/lib/foreman_inventory_upload/async/queue_for_upload_job.rb +1 -0
  11. data/lib/foreman_inventory_upload/async/upload_report_direct_job.rb +16 -2
  12. data/lib/foreman_inventory_upload/generators/archived_report.rb +4 -4
  13. data/lib/foreman_inventory_upload/generators/slice.rb +55 -12
  14. data/lib/foreman_inventory_upload.rb +69 -0
  15. data/lib/foreman_rh_cloud/plugin.rb +24 -11
  16. data/lib/foreman_rh_cloud/version.rb +1 -1
  17. data/package.json +6 -13
  18. data/test/controllers/insights_cloud/api/advisor_engine_controller_test.rb +4 -15
  19. data/test/controllers/insights_cloud/ui_requests_controller_test.rb +217 -5
  20. data/test/jobs/generate_host_report_test.rb +1 -1
  21. data/test/jobs/host_inventory_report_job_test.rb +72 -0
  22. data/test/jobs/queue_for_upload_job_test.rb +4 -1
  23. data/test/jobs/upload_report_direct_job_test.rb +28 -7
  24. data/test/unit/archived_report_generator_test.rb +21 -0
  25. data/test/unit/foreman_inventory_upload_host_report_path_test.rb +111 -0
  26. data/test/unit/rh_cloud_permissions_test.rb +0 -2
  27. data/test/unit/services/foreman_rh_cloud/insights_api_forwarder_test.rb +189 -356
  28. data/test/unit/slice_generator_test.rb +28 -0
  29. data/webpack/ForemanInventoryUpload/Components/Dashboard/Dashboard.js +1 -0
  30. data/webpack/ForemanInventoryUpload/Components/TaskProgress/TaskProgress.js +8 -2
  31. data/webpack/ForemanInventoryUpload/SubscriptionsPageExtension/InventoryAutoUpload/InventoryAutoUpload.js +3 -1
  32. data/webpack/ForemanInventoryUpload/SubscriptionsPageExtension/InventoryAutoUpload/__tests__/InventoryAutoUpload.test.js +23 -0
  33. data/webpack/HostsIndexExtensions/VulnerabilityAnalysisActions.js +1 -1
  34. data/webpack/test_setup.js +18 -0
  35. metadata +3 -6
  36. data/app/controllers/foreman_inventory_upload/api/tasks_controller.rb +0 -110
  37. data/app/services/foreman_rh_cloud/hits_uploader.rb +0 -50
  38. data/lib/tasks/hybrid_cloud.rake +0 -132
  39. data/test/unit/services/foreman_rh_cloud/hits_uploader_test.rb +0 -131
@@ -249,6 +249,34 @@ class SliceGeneratorTest < ActiveSupport::TestCase
249
249
  assert_nil fact_values['virtual_host_name']
250
250
  end
251
251
 
252
+ test 'generates valid JSON with minimal data collection for a physical host with no system profile facts' do
253
+ Setting[:insights_minimal_data_collection] = true
254
+ ForemanRhCloud.stubs(:with_iop_smart_proxy?).returns(false)
255
+ # No facts created: simulates a physical host that reports none of the
256
+ # cpu/memory facts, has no installed products, is not a hypervisor, and has
257
+ # no hypervisor host. All four conditions that previously produced a
258
+ # trailing comma after an empty system_profile object are true here.
259
+
260
+ batch = Host.where(id: @host.id).in_batches.first
261
+ generator = create_generator(batch)
262
+
263
+ json_str = generator.render
264
+ # assert_nothing_raised makes explicit that the purpose of this test is
265
+ # to verify no trailing commas produce a JSON parse error
266
+ actual = nil
267
+ assert_nothing_raised { actual = JSON.parse(json_str.join("\n")) }
268
+
269
+ assert_equal '00000000-0000-0000-0000-000000000000', actual['report_slice_id']
270
+ assert_not_nil(actual_host = actual['hosts'].first)
271
+ assert_equal 1, generator.hosts_count
272
+ assert_equal '1234', actual_host['account']
273
+ assert_not_nil actual_host['subscription_manager_id']
274
+ assert_not_nil actual_host['system_profile']
275
+ assert_empty actual_host['system_profile']
276
+ assert_nil actual_host['cpu_socket(s)']
277
+ assert_nil actual_host['facts']
278
+ end
279
+
252
280
  test 'packages are excluded in the report with minimal data collection' do
253
281
  Setting[:exclude_installed_packages] = false
254
282
  Setting[:insights_minimal_data_collection] = true
@@ -43,6 +43,7 @@ Dashboard.propTypes = {
43
43
  ended_at: PropTypes.string,
44
44
  duration: PropTypes.number,
45
45
  report_file_path: PropTypes.string,
46
+ uploaded: PropTypes.bool,
46
47
  }),
47
48
  }),
48
49
  onTaskStart: PropTypes.func,
@@ -271,9 +271,14 @@ const TaskProgress = ({
271
271
  </DescriptionListDescription>
272
272
  </DescriptionListGroup>
273
273
  <DescriptionListGroup>
274
- <DescriptionListTerm>{__('Report saved to')}</DescriptionListTerm>
274
+ <DescriptionListTerm>{__('Report')}</DescriptionListTerm>
275
275
  <DescriptionListDescription>
276
- {!isStartingNewTask && task.report_file_path}
276
+ {!isStartingNewTask && task.uploaded && __('Report uploaded')}
277
+ {!isStartingNewTask &&
278
+ !task.uploaded &&
279
+ task.state === 'stopped' &&
280
+ task.result === 'success' &&
281
+ __('Report generated')}
277
282
  </DescriptionListDescription>
278
283
  </DescriptionListGroup>
279
284
  </DescriptionList>
@@ -317,6 +322,7 @@ TaskProgress.propTypes = {
317
322
  ended_at: PropTypes.string,
318
323
  duration: PropTypes.number,
319
324
  report_file_path: PropTypes.string,
325
+ uploaded: PropTypes.bool,
320
326
  }),
321
327
  title: PropTypes.string,
322
328
  emptyMessage: PropTypes.string,
@@ -13,6 +13,7 @@ import {
13
13
  import { InfoAltIcon, CaretRightIcon } from '@patternfly/react-icons';
14
14
  import { translate as __ } from 'foremanReact/common/I18n';
15
15
  import { foremanUrl } from '../../../ForemanRhCloudHelpers';
16
+ import { useIopConfig } from '../../../common/Hooks/ConfigHooks';
16
17
  import SwitcherPF4 from '../../../common/Switcher/SwitcherPF4';
17
18
  import { settingsDict } from '../../Components/InventorySettings/AdvancedSetting/AdvancedSettingsConstants';
18
19
  import InventorySettings from '../../Components/InventorySettings/InventorySettings';
@@ -22,6 +23,7 @@ const InventoryAutoUploadSwitcher = ({
22
23
  setSetting,
23
24
  getSettings,
24
25
  }) => {
26
+ const isIop = useIopConfig();
25
27
  useEffect(() => {
26
28
  getSettings();
27
29
  }, [getSettings]);
@@ -80,7 +82,7 @@ const InventoryAutoUploadSwitcher = ({
80
82
  rel="noopener noreferrer"
81
83
  >
82
84
  <strong>
83
- {__('Configure')}
85
+ {isIop ? __('Administer') : __('Insights')}
84
86
  {' > '}
85
87
  {__('Inventory Upload')}
86
88
  </strong>
@@ -2,6 +2,11 @@ import React from 'react';
2
2
  import { render, screen } from '@testing-library/react';
3
3
  import InventoryAutoUpload from '../InventoryAutoUpload';
4
4
 
5
+ let mockIsIop = false;
6
+ jest.mock('../../../../common/Hooks/ConfigHooks', () => ({
7
+ useIopConfig: () => mockIsIop,
8
+ }));
9
+
5
10
  jest.mock(
6
11
  '../../../Components/InventorySettings/InventorySettings',
7
12
  () => () => <div data-testid="inventory-settings">InventorySettings</div>
@@ -15,6 +20,10 @@ describe('InventoryAutoUpload', () => {
15
20
  ...overrides,
16
21
  });
17
22
 
23
+ beforeEach(() => {
24
+ mockIsIop = false;
25
+ });
26
+
18
27
  it('renders the heading', () => {
19
28
  render(<InventoryAutoUpload {...buildProps()} />);
20
29
  expect(screen.getByText('Red Hat Cloud Inventory')).toBeTruthy();
@@ -39,4 +48,18 @@ describe('InventoryAutoUpload', () => {
39
48
  render(<InventoryAutoUpload {...props} />);
40
49
  expect(props.getSettings).toHaveBeenCalled();
41
50
  });
51
+
52
+ it('points to the Insights menu in regular mode', () => {
53
+ mockIsIop = false;
54
+ render(<InventoryAutoUpload {...buildProps()} />);
55
+ expect(screen.getByText(/Insights/)).toBeTruthy();
56
+ expect(screen.queryByText(/Administer/)).toBeNull();
57
+ });
58
+
59
+ it('points to the Administer menu in IoP mode', () => {
60
+ mockIsIop = true;
61
+ render(<InventoryAutoUpload {...buildProps()} />);
62
+ expect(screen.getByText(/Administer/)).toBeTruthy();
63
+ expect(screen.queryByText(/Insights/)).toBeNull();
64
+ });
42
65
  });
@@ -19,7 +19,7 @@ const handleToggle = (uuid, newOptOutValue, hostId) => {
19
19
  opt_out: newOptOutValue,
20
20
  },
21
21
  headers: {
22
- 'Content-Type': 'application/vnd.api+json', // eslint-disable-line spellcheck/spell-checker
22
+ 'Content-Type': 'application/vnd.api+json',
23
23
  },
24
24
 
25
25
  // Update CVE API cache data to reflect new opt_out status
@@ -1 +1,19 @@
1
1
  import 'foremanJSTestSetup';
2
+
3
+ /* eslint-disable global-require, react/prop-types */
4
+ jest.mock(
5
+ '@patternfly/react-core/deprecated',
6
+ () => {
7
+ const React = require('react');
8
+
9
+ return {
10
+ Dropdown: ({ children }) => React.createElement('div', null, children),
11
+ DropdownItem: ({ children, ...props }) =>
12
+ React.createElement('div', props, children),
13
+ KebabToggle: props =>
14
+ React.createElement('button', { type: 'button', ...props }),
15
+ };
16
+ },
17
+ { virtual: true }
18
+ );
19
+ /* eslint-enable global-require, react/prop-types */
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: foreman_rh_cloud
3
3
  version: !ruby/object:Gem::Version
4
- version: 15.0.0
4
+ version: 15.0.2
5
5
  platform: ruby
6
6
  authors:
7
7
  - Foreman Red Hat Cloud team
@@ -78,7 +78,6 @@ files:
78
78
  - app/controllers/concerns/inventory_upload/report_actions.rb
79
79
  - app/controllers/concerns/inventory_upload/task_actions.rb
80
80
  - app/controllers/foreman_inventory_upload/accounts_controller.rb
81
- - app/controllers/foreman_inventory_upload/api/tasks_controller.rb
82
81
  - app/controllers/foreman_inventory_upload/cloud_status_controller.rb
83
82
  - app/controllers/foreman_inventory_upload/missing_hosts_controller.rb
84
83
  - app/controllers/foreman_inventory_upload/reports_controller.rb
@@ -111,7 +110,6 @@ files:
111
110
  - app/services/foreman_rh_cloud/cloud_request.rb
112
111
  - app/services/foreman_rh_cloud/cloud_request_forwarder.rb
113
112
  - app/services/foreman_rh_cloud/hit_remediations_retriever.rb
114
- - app/services/foreman_rh_cloud/hits_uploader.rb
115
113
  - app/services/foreman_rh_cloud/insights_api_forwarder.rb
116
114
  - app/services/foreman_rh_cloud/insights_status_cleaner.rb
117
115
  - app/services/foreman_rh_cloud/remediations_retriever.rb
@@ -200,7 +198,6 @@ files:
200
198
  - lib/inventory_sync/async/inventory_self_host_sync.rb
201
199
  - lib/inventory_sync/async/query_inventory_job.rb
202
200
  - lib/tasks/foreman_rh_cloud_tasks.rake
203
- - lib/tasks/hybrid_cloud.rake
204
201
  - lib/tasks/insights.rake
205
202
  - lib/tasks/rh_cloud_inventory.rake
206
203
  - locale/Makefile
@@ -254,6 +251,7 @@ files:
254
251
  - test/test_plugin_helper.rb
255
252
  - test/unit/archived_report_generator_test.rb
256
253
  - test/unit/fact_helpers_test.rb
254
+ - test/unit/foreman_inventory_upload_host_report_path_test.rb
257
255
  - test/unit/foreman_rh_cloud_iop_metadata_test.rb
258
256
  - test/unit/foreman_rh_cloud_self_host_test.rb
259
257
  - test/unit/insights_facet_test.rb
@@ -269,7 +267,6 @@ files:
269
267
  - test/unit/services/foreman_rh_cloud/cloud_request_forwarder_test.rb
270
268
  - test/unit/services/foreman_rh_cloud/cloud_status_service_test.rb
271
269
  - test/unit/services/foreman_rh_cloud/hit_remediations_retriever_test.rb
272
- - test/unit/services/foreman_rh_cloud/hits_uploader_test.rb
273
270
  - test/unit/services/foreman_rh_cloud/insights_api_forwarder_test.rb
274
271
  - test/unit/services/foreman_rh_cloud/insights_status_cleaner_test.rb
275
272
  - test/unit/services/foreman_rh_cloud/rules_ingester_test.rb
@@ -595,6 +592,7 @@ test_files:
595
592
  - test/test_plugin_helper.rb
596
593
  - test/unit/archived_report_generator_test.rb
597
594
  - test/unit/fact_helpers_test.rb
595
+ - test/unit/foreman_inventory_upload_host_report_path_test.rb
598
596
  - test/unit/foreman_rh_cloud_iop_metadata_test.rb
599
597
  - test/unit/foreman_rh_cloud_self_host_test.rb
600
598
  - test/unit/insights_facet_test.rb
@@ -610,7 +608,6 @@ test_files:
610
608
  - test/unit/services/foreman_rh_cloud/cloud_request_forwarder_test.rb
611
609
  - test/unit/services/foreman_rh_cloud/cloud_status_service_test.rb
612
610
  - test/unit/services/foreman_rh_cloud/hit_remediations_retriever_test.rb
613
- - test/unit/services/foreman_rh_cloud/hits_uploader_test.rb
614
611
  - test/unit/services/foreman_rh_cloud/insights_api_forwarder_test.rb
615
612
  - test/unit/services/foreman_rh_cloud/insights_status_cleaner_test.rb
616
613
  - test/unit/services/foreman_rh_cloud/rules_ingester_test.rb
@@ -1,110 +0,0 @@
1
- module ForemanInventoryUpload
2
- module Api
3
- class TasksController < ::Api::V2::BaseController
4
- ACTION_TYPES = [
5
- 'ForemanInventoryUpload::Async::HostInventoryReportJob',
6
- 'ForemanInventoryUpload::Async::UploadReportDirectJob',
7
- ].freeze
8
-
9
- # GET /foreman_inventory_upload/api/tasks/current
10
- # Returns current running/active tasks for inventory operations
11
- def current
12
- organization_id = validate_organization_id if params[:organization_id].present?
13
- return if performed?
14
-
15
- tasks = ForemanTasks::Task
16
- .active
17
- .for_action_types(ACTION_TYPES)
18
- .select_duration
19
-
20
- if organization_id.present?
21
- tasks = tasks.joins(:links)
22
- .where(foreman_tasks_links: {
23
- resource_type: 'Organization',
24
- resource_id: organization_id,
25
- })
26
- end
27
-
28
- render json: {
29
- tasks: tasks.map { |task| task_json(task) },
30
- }
31
- end
32
-
33
- # GET /foreman_inventory_upload/api/tasks/history
34
- # Returns recent task history for inventory operations
35
- def history
36
- organization_id = validate_organization_id if params[:organization_id].present?
37
- return if performed?
38
-
39
- limit = validated_limit
40
-
41
- tasks = ForemanTasks::Task
42
- .for_action_types(ACTION_TYPES)
43
- .select_duration
44
- .order('started_at DESC')
45
- .limit(limit)
46
-
47
- if organization_id.present?
48
- tasks = tasks.joins(:links)
49
- .where(foreman_tasks_links: {
50
- resource_type: 'Organization',
51
- resource_id: organization_id,
52
- })
53
- end
54
-
55
- render json: {
56
- tasks: tasks.map { |task| task_json(task) },
57
- }
58
- end
59
-
60
- private
61
-
62
- def controller_permission
63
- 'foreman_rh_cloud'
64
- end
65
-
66
- def task_json(task)
67
- {
68
- id: task.id,
69
- label: task.label,
70
- action: task.action,
71
- state: task.state,
72
- result: task.result,
73
- progress: task.progress,
74
- started_at: task.started_at,
75
- ended_at: task.ended_at,
76
- duration: task.duration&.to_f,
77
- humanized: task.humanized,
78
- report_file_path: task_report_file_path(task),
79
- }
80
- end
81
-
82
- def task_report_file_path(task)
83
- return nil unless task.state == 'stopped' && task.result == 'success'
84
- return nil unless task.action == 'ForemanInventoryUpload::Async::HostInventoryReportJob'
85
-
86
- task.main_action&.output&.[]('report_file')
87
- end
88
-
89
- def validate_organization_id
90
- org_id = params[:organization_id].to_i
91
- if org_id.zero?
92
- render json: { message: 'Invalid organization_id parameter' }, status: :bad_request
93
- return nil
94
- end
95
-
96
- begin
97
- Organization.find(org_id).id
98
- rescue ActiveRecord::RecordNotFound
99
- render json: { message: "Organization with id #{org_id} not found" }, status: :not_found
100
- nil
101
- end
102
- end
103
-
104
- def validated_limit
105
- limit = params[:limit]&.to_i || 10
106
- limit.clamp(1, 100)
107
- end
108
- end
109
- end
110
- end
@@ -1,50 +0,0 @@
1
- module ForemanRhCloud
2
- class HitsUploader
3
- def initialize(host:, payload:, uuid: nil)
4
- @host = host
5
- @uuid = uuid
6
- @payload = payload
7
- end
8
-
9
- def upload!
10
- ActiveRecord::Base.transaction do
11
- update_facets
12
- update_hits
13
- update_rules_and_resolutions
14
- update_details
15
- end
16
- end
17
-
18
- private
19
-
20
- def update_facets
21
- facet = InsightsFacet.find_or_create_by(host_id: @host.id)
22
- facet.update!(uuid: @uuid) if @uuid.present?
23
- @host.reload
24
- end
25
-
26
- def update_hits
27
- facet = @host.insights
28
- facet.hits.delete_all
29
- hits = @payload[:hits]
30
- # rubocop:disable Rails/SkipsModelValidations
31
- facet.hits.insert_all(hits) if hits.present?
32
- # rubocop:enable Rails/SkipsModelValidations
33
- InsightsFacet.reset_counters(facet.id, :hits_count)
34
- end
35
-
36
- def update_rules_and_resolutions
37
- return if @payload[:rules].blank?
38
- rule_ids = @payload[:rules].map { |rule| rule[:rule_id] }
39
- has_missing_rules = InsightsRule.where(rule_id: rule_ids).count != rule_ids.count
40
- RulesIngester.new.ingest_rules_and_resolutions! if has_missing_rules
41
- end
42
-
43
- def update_details
44
- return if @payload[:details].blank?
45
- fact_name = FactName.where(name: "insights::hit_details", short_name: 'insights_details').first_or_create
46
- fact_value = @host.fact_values.where(fact_name: fact_name).first_or_create
47
- fact_value.update(value: @payload[:details])
48
- end
49
- end
50
- end
@@ -1,132 +0,0 @@
1
- require 'io/console'
2
- require 'uri'
3
-
4
- def logger
5
- @logger ||= Logger.new(STDOUT)
6
- end
7
-
8
- namespace :rh_cloud do
9
- desc 'Register Satellite Organization with Hybrid Cloud API.'
10
- # This task registers the Satellite Organization with the Hybrid Cloud API.
11
- # It requires the user to input their organization ID, Insights URL, and token.
12
- # The task will then send a POST request to the Hybrid Cloud API to register the organization.
13
- # The response will be logged, and any errors will be caught and logged as well.
14
- # The task will exit with an error message if the organization does not have a manifest imported or if the token is not entered.
15
- # The task will also log a warning if the custom URL is not set and the default one is used.
16
- task hybridcloud_register: [:environment] do
17
- include ::ForemanRhCloud::CertAuth
18
- include ::InsightsCloud::CandlepinCache
19
-
20
- def default_registrations_url
21
- URI.join(ForemanRhCloud.base_url, '/api/identity/certificate/registrations').to_s
22
- end
23
-
24
- # Helper method to get the registrations URL, with a warning for default usage
25
- def registrations_url(custom_url)
26
- if custom_url.empty?
27
- logger.warn("Custom url is not set, using the default one: #{default_registrations_url}")
28
- default_registrations_url
29
- else
30
- if URI(custom_url).scheme.nil?
31
- logger.warn("Custom URL lacks a scheme; prepending https:// prefix.")
32
- custom_url = "https://" + custom_url
33
- end
34
- custom_url
35
- end
36
- end
37
-
38
- def get_organization(user_org_id)
39
- maybe_organization = Organization.find_by(id: user_org_id)
40
- if maybe_organization.nil?
41
- logger.error("Organization with ID '#{user_org_id}' not found.")
42
- exit(1)
43
- end
44
- maybe_organization
45
- end
46
-
47
- def get_uid(organization)
48
- maybe_uid = cp_owner_id(organization)
49
- if maybe_uid.nil?
50
- logger.error("Organization '#{organization}' does not have a manifest imported.")
51
- exit(1)
52
- end
53
- maybe_uid
54
- end
55
-
56
- # --- Input Collection ---
57
- puts "Paste in your organization ID, this can be retrieved with the command: hammer organization list"
58
- loop do
59
- input = STDIN.gets.chomp
60
- if input.match?(/^\d+$/) # Checks if input consists only of digits
61
- @user_org_id = input.to_i
62
- break
63
- else
64
- puts "Invalid input. Please enter a numeric organization ID."
65
- end
66
- end
67
-
68
- puts "\n" + "-" * 50 + "\n\n"
69
- puts "Paste in your custom Insights URL. If nothing is entered, the default will be used (#{default_registrations_url})."
70
- insights_user_input = STDIN.gets.chomp
71
-
72
- puts "\n" + "-" * 50 + "\n\n"
73
- puts 'Paste in your Hybrid Cloud API token, output will be hidden.'
74
- puts 'This token can be retrieved from the Hybrid Cloud console.'
75
- token = STDIN.noecho(&:gets).chomp
76
- if token.empty?
77
- logger.error('Token was not entered.')
78
- exit(1)
79
- end
80
-
81
- # --- Data Preparation ---
82
-
83
- organization = get_organization(@user_org_id)
84
- uid = get_uid(organization)
85
- hostname = ForemanRhCloud.foreman_host_name
86
- insights_url = registrations_url(insights_user_input)
87
-
88
- # --- API Request ---
89
-
90
- headers = {
91
- Authorization: "Bearer #{token}",
92
- }
93
-
94
- payload = {
95
- 'uid': uid,
96
- "display_name": "#{hostname}+#{organization.label}",
97
- }
98
-
99
- begin
100
- response = execute_cloud_request(
101
- organization: organization,
102
- method: :post,
103
- url: insights_url,
104
- headers: headers,
105
- payload: payload.to_json
106
- )
107
- logger.debug("Cloud request completed: status=#{response.code}, body_preview=#{response.body&.slice(0, 200)}")
108
- rescue RestClient::Unauthorized => _ex
109
- # Add a more specific rescue for 401 Unauthorized errors
110
- logger.error('Registration failed: Your token is invalid or unauthorized. Please check your token and try again.')
111
- # Optionally, you can still log the full debug info if helpful for advanced troubleshooting
112
- # logger.debug(ex.backtrace.join("\n"))
113
- exit(1)
114
- rescue RestClient::ExceptionWithResponse => ex
115
- # This catches any RestClient exception that has a response (like 400, 403, 404, 500, etc.)
116
- status_code = begin
117
- ex.response.code
118
- rescue StandardError
119
- "unknown"
120
- end
121
- logger.error("Registration failed with HTTP status #{status_code}: #{ex.message}")
122
- logger.debug("Response body (if available): #{ex.response.body}")
123
- exit(1)
124
- rescue StandardError => ex
125
- # This is the catch-all for any other unexpected errors
126
- logger.error("An unexpected error occurred during registration: #{ex.message}")
127
- exit(1)
128
- end
129
-
130
- logger.info("Satellite Organization '#{organization.label}' (ID: #{@user_org_id}) successfully registered.")
131
- end
132
- end
@@ -1,131 +0,0 @@
1
- require 'test_plugin_helper'
2
-
3
- class HitsUploaderTest < ActiveSupport::TestCase
4
- PAYLOAD = {
5
- resolutions: [
6
- {
7
- rule_id: "R123",
8
- description: "Apply security patch to fix vulnerability CVE-2025-0001.",
9
- needs_reboot: true,
10
- resolution_risk: "Medium",
11
- resolution_type: "fix",
12
- },
13
- {
14
- rule_id: "R124",
15
- description: "Update configuration file to improve system stability.",
16
- needs_reboot: false,
17
- resolution_risk: "Low",
18
- resolution_type: "fix",
19
- },
20
- ],
21
- rules: [
22
- {
23
- rule_id: "R123",
24
- description: "Security patch for CVE-2025-0001.",
25
- category_name: "Security",
26
- impact_name: "High",
27
- summary: "Fixes critical vulnerability.",
28
- generic: "Security updates are mandatory.",
29
- reason: "Vulnerability exposed in external audit.",
30
- total_risk: 5,
31
- reboot_required: true,
32
- more_info: "https://example.com/security-update",
33
- rating: 4.8,
34
- },
35
- {
36
- rule_id: "R124",
37
- description: "Configuration update to improve performance.",
38
- category_name: "Availability",
39
- impact_name: "Medium",
40
- summary: "Improves application stability and reduces crashes.",
41
- generic: "Periodic updates recommended.",
42
- reason: "Frequent crashes observed in logs.",
43
- total_risk: 3,
44
- reboot_required: false,
45
- more_info: "https://example.com/config-update",
46
- rating: 4.0,
47
- },
48
- ],
49
- hits: [
50
- {
51
- rule_id: "R123",
52
- title: "Critical Vulnerability Patch",
53
- solution_url: "https://example.com/solution",
54
- total_risk: 5,
55
- likelihood: 4,
56
- publish_date: "2025-01-01",
57
- results_url: "https://example.com/results",
58
- },
59
- {
60
- rule_id: "R124",
61
- title: "Configuration Update",
62
- solution_url: "https://example.com/config-solution",
63
- total_risk: 3,
64
- likelihood: 3,
65
- publish_date: "2025-01-02",
66
- results_url: "https://example.com/config-results",
67
- },
68
- ],
69
- details: "{\"summary\": \"Detected issues and resolutions applied successfully.\"}",
70
- }.freeze
71
-
72
- setup do
73
- @host = FactoryBot.create(:host)
74
- @uuid = SecureRandom.uuid
75
- rules_resolutions = [PAYLOAD[:rules], PAYLOAD[:resolutions]]
76
- ForemanRhCloud::RulesIngester.any_instance.
77
- expects(:fetch_rules_and_resolutions).returns(rules_resolutions)
78
- @uploader = ForemanRhCloud::HitsUploader.new(host: @host, payload: PAYLOAD, uuid: @uuid)
79
- @uploader.upload!
80
- @host.reload
81
- end
82
-
83
- test 'facets' do
84
- assert_equal @uuid, @host.insights_facet.uuid
85
- end
86
-
87
- test 'hits' do
88
- assert_equal PAYLOAD[:hits].count, @host.insights_facet.hits_count
89
- assert_includes @host.insights_facet.hits.pluck(:rule_id), "R124"
90
- end
91
-
92
- test 'assert reupload does not trigger rules download' do
93
- # rules must already be in the database so dont retrigger
94
- # rules download.
95
- ForemanRhCloud::RulesIngester.any_instance.
96
- expects(:ingest_rules_and_resolutions!).never
97
- @uploader.upload!
98
- end
99
-
100
- test "resolutions" do
101
- assert_equal 2, InsightsResolution.where(rule_id: ["R123", "R124"]).count
102
- end
103
-
104
- test "details" do
105
- fact_name = FactName.where(name: "insights::hit_details").first
106
- fact_value = @host.fact_values.where(fact_name: fact_name).first
107
- refute_nil fact_value
108
- assert_equal PAYLOAD[:details], fact_value.value
109
- end
110
-
111
- test "empty payload" do
112
- payload = {
113
- resolutions: [],
114
- rules: [],
115
- hits: [],
116
- details: "",
117
- }
118
-
119
- @host = FactoryBot.create(:host)
120
- @uuid = SecureRandom.uuid
121
- uploader = ForemanRhCloud::HitsUploader.new(host: @host, payload: payload, uuid: @uuid)
122
- uploader.upload!
123
- @host.reload
124
- assert_equal @uuid, @host.insights_facet.uuid
125
- assert_empty @host.insights_facet.hits
126
- assert_equal 0, @host.insights_facet.hits_count
127
- fact_name = FactName.where(name: "insights::hit_details").first
128
- fact_value = @host.fact_values.where(fact_name: fact_name).first
129
- assert_nil fact_value
130
- end
131
- end