openc3 7.5.1 → 7.6.0

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 (169) hide show
  1. checksums.yaml +4 -4
  2. data/Gemfile +0 -0
  3. data/bin/openc3cli +82 -5
  4. data/data/config/_params.yaml +3 -0
  5. data/data/config/command_modifiers.yaml +5 -3
  6. data/data/config/default_plugins.yaml +1 -0
  7. data/data/config/interface_modifiers.yaml +17 -1
  8. data/data/config/item_modifiers.yaml +24 -1
  9. data/data/config/microservice.yaml +15 -1
  10. data/data/config/parameter_modifiers.yaml +4 -4
  11. data/data/config/plugins.yaml +511 -3
  12. data/data/config/settings.yaml +17 -0
  13. data/data/config/target.yaml +53 -0
  14. data/data/config/telemetry.yaml +58 -2
  15. data/data/config/widgets.yaml +30 -0
  16. data/lib/openc3/accessors/accessor.rb +14 -2
  17. data/lib/openc3/accessors/binary_accessor.rb +25 -5
  18. data/lib/openc3/api/CLAUDE.md +1 -0
  19. data/lib/openc3/api/api.rb +1 -0
  20. data/lib/openc3/api/cmd_api.rb +9 -1
  21. data/lib/openc3/api/interface_api.rb +7 -2
  22. data/lib/openc3/api/limits_api.rb +93 -41
  23. data/lib/openc3/api/router_api.rb +7 -2
  24. data/lib/openc3/api/settings_api.rb +4 -1
  25. data/lib/openc3/api/shared_resource_api.rb +107 -0
  26. data/lib/openc3/api/tlm_api.rb +10 -0
  27. data/lib/openc3/interfaces/http_client_interface.rb +84 -27
  28. data/lib/openc3/interfaces/protocols/preidentified_protocol.rb +6 -2
  29. data/lib/openc3/interfaces/tcpip_server_interface.rb +205 -125
  30. data/lib/openc3/io/json_api.rb +2 -10
  31. data/lib/openc3/io/json_api_object.rb +2 -10
  32. data/lib/openc3/logs/packet_log_writer.rb +8 -3
  33. data/lib/openc3/microservices/decom_common.rb +4 -1
  34. data/lib/openc3/microservices/decom_microservice.rb +52 -6
  35. data/lib/openc3/microservices/interface_decom_common.rb +13 -0
  36. data/lib/openc3/microservices/interface_microservice.rb +50 -11
  37. data/lib/openc3/microservices/limits_group_microservice.rb +513 -0
  38. data/lib/openc3/microservices/log_microservice.rb +22 -8
  39. data/lib/openc3/microservices/microservice.rb +8 -2
  40. data/lib/openc3/microservices/multi_microservice.rb +76 -22
  41. data/lib/openc3/microservices/queue_microservice.rb +29 -24
  42. data/lib/openc3/migrations/20260704000000_default_bridge.rb +1 -2
  43. data/lib/openc3/migrations/20261103000001_limits_group_backfill.rb +193 -0
  44. data/lib/openc3/models/bridge_model.rb +3 -3
  45. data/lib/openc3/models/cvt_model.rb +3 -1
  46. data/lib/openc3/models/host_interface_microservice_model.rb +4 -4
  47. data/lib/openc3/models/interface_model.rb +27 -7
  48. data/lib/openc3/models/microservice_group.rb +167 -0
  49. data/lib/openc3/models/microservice_model.rb +88 -2
  50. data/lib/openc3/models/panel_model.rb +109 -0
  51. data/lib/openc3/models/plugin_model.rb +1006 -26
  52. data/lib/openc3/models/plugin_store_model.rb +6 -1
  53. data/lib/openc3/models/protected_storage_model.rb +64 -0
  54. data/lib/openc3/models/queue_model.rb +19 -10
  55. data/lib/openc3/models/scope_model.rb +80 -3
  56. data/lib/openc3/models/setting_model.rb +2 -2
  57. data/lib/openc3/models/shared_resource_model.rb +381 -0
  58. data/lib/openc3/models/target_model.rb +324 -68
  59. data/lib/openc3/operators/microservice_operator.rb +76 -9
  60. data/lib/openc3/operators/operator.rb +29 -0
  61. data/lib/openc3/packets/commands.rb +16 -16
  62. data/lib/openc3/packets/limits.rb +2 -0
  63. data/lib/openc3/packets/packet.rb +75 -4
  64. data/lib/openc3/packets/packet_config.rb +152 -13
  65. data/lib/openc3/packets/packet_item.rb +35 -14
  66. data/lib/openc3/packets/packet_item_limits.rb +67 -6
  67. data/lib/openc3/packets/parsers/limits_parser.rb +69 -2
  68. data/lib/openc3/packets/parsers/packet_item_parser.rb +6 -0
  69. data/lib/openc3/packets/parsers/packet_parser.rb +45 -0
  70. data/lib/openc3/packets/parsers/state_parser.rb +1 -1
  71. data/lib/openc3/script/CLAUDE.md +1 -0
  72. data/lib/openc3/script/api_shared.rb +17 -9
  73. data/lib/openc3/script/calendar.rb +18 -6
  74. data/lib/openc3/script/commands.rb +11 -9
  75. data/lib/openc3/script/critical_cmd.rb +22 -2
  76. data/lib/openc3/script/metadata.rb +30 -4
  77. data/lib/openc3/script/plugins.rb +8 -0
  78. data/lib/openc3/script/script.rb +8 -24
  79. data/lib/openc3/script/web_socket_api.rb +23 -17
  80. data/lib/openc3/system/system.rb +9 -3
  81. data/lib/openc3/top_level.rb +17 -0
  82. data/lib/openc3/topics/command_topic.rb +7 -1
  83. data/lib/openc3/topics/decom_interface_topic.rb +9 -3
  84. data/lib/openc3/topics/discovery_topic.rb +84 -0
  85. data/lib/openc3/topics/limits_event_topic.rb +236 -17
  86. data/lib/openc3/topics/telemetry_decom_topic.rb +12 -3
  87. data/lib/openc3/topics/topic.rb +2 -1
  88. data/lib/openc3/utilities/authentication.rb +67 -16
  89. data/lib/openc3/utilities/cli_generator.rb +117 -25
  90. data/lib/openc3/utilities/client_ip_header_filter.rb +38 -0
  91. data/lib/openc3/utilities/config_overlay.rb +24 -1
  92. data/lib/openc3/utilities/cosmos_rails_formatter.rb +18 -10
  93. data/lib/openc3/utilities/hardware_discovery.rb +279 -0
  94. data/lib/openc3/utilities/limits_rollup.rb +81 -0
  95. data/lib/openc3/utilities/local_mode.rb +48 -5
  96. data/lib/openc3/utilities/questdb_client.rb +130 -22
  97. data/lib/openc3/utilities/reingest_job.rb +12 -3
  98. data/lib/openc3/utilities/running_script.rb +206 -49
  99. data/lib/openc3/utilities/script.rb +24 -12
  100. data/lib/openc3/utilities/script_env.rb +164 -0
  101. data/lib/openc3/utilities/script_message_signing.rb +133 -0
  102. data/lib/openc3/utilities/store_autoload.rb +32 -1
  103. data/lib/openc3/utilities/store_queued.rb +5 -1
  104. data/lib/openc3/version.rb +6 -6
  105. data/templates/command_validator/command_validator.py +9 -9
  106. data/templates/{tool_react/pnpm-workspace.yaml → panel/.prettierrc.cjs} +7 -5
  107. data/templates/panel/Rakefile +24 -0
  108. data/templates/panel/package.json +17 -0
  109. data/templates/{tool_angular → panel}/pnpm-workspace.yaml +5 -0
  110. data/templates/panel/src/Panel.js +52 -0
  111. data/templates/panel/src/Panel.vue +60 -0
  112. data/templates/panel/src/panelSdk.js +24 -0
  113. data/templates/panel/vite-Panel.config.js +43 -0
  114. data/templates/tool_vue/package.json +3 -3
  115. data/templates/widget/package.json +2 -2
  116. metadata +24 -56
  117. data/templates/tool_angular/.editorconfig +0 -16
  118. data/templates/tool_angular/.gitignore +0 -44
  119. data/templates/tool_angular/.vscode/extensions.json +0 -4
  120. data/templates/tool_angular/.vscode/launch.json +0 -20
  121. data/templates/tool_angular/.vscode/tasks.json +0 -42
  122. data/templates/tool_angular/angular.json +0 -111
  123. data/templates/tool_angular/extra-webpack.config.js +0 -8
  124. data/templates/tool_angular/package.json +0 -48
  125. data/templates/tool_angular/src/app/app-routing.module.ts +0 -15
  126. data/templates/tool_angular/src/app/app.component.html +0 -22
  127. data/templates/tool_angular/src/app/app.component.scss +0 -18
  128. data/templates/tool_angular/src/app/app.component.spec.ts +0 -29
  129. data/templates/tool_angular/src/app/app.component.ts +0 -52
  130. data/templates/tool_angular/src/app/app.module.ts +0 -30
  131. data/templates/tool_angular/src/app/custom-overlay-container.ts +0 -17
  132. data/templates/tool_angular/src/app/empty-route/empty-route.component.ts +0 -7
  133. data/templates/tool_angular/src/app/openc3-api.d.ts +0 -1
  134. data/templates/tool_angular/src/assets/.gitkeep +0 -0
  135. data/templates/tool_angular/src/environments/environment.prod.ts +0 -3
  136. data/templates/tool_angular/src/environments/environment.ts +0 -16
  137. data/templates/tool_angular/src/favicon.ico +0 -0
  138. data/templates/tool_angular/src/index.html +0 -13
  139. data/templates/tool_angular/src/main.single-spa.ts +0 -40
  140. data/templates/tool_angular/src/single-spa/asset-url.ts +0 -12
  141. data/templates/tool_angular/src/single-spa/single-spa-props.ts +0 -8
  142. data/templates/tool_angular/src/styles.scss +0 -1
  143. data/templates/tool_angular/tsconfig.app.json +0 -13
  144. data/templates/tool_angular/tsconfig.json +0 -33
  145. data/templates/tool_angular/tsconfig.spec.json +0 -14
  146. data/templates/tool_react/.eslintrc +0 -7
  147. data/templates/tool_react/.gitignore +0 -71
  148. data/templates/tool_react/.prettierignore +0 -8
  149. data/templates/tool_react/babel.config.json +0 -29
  150. data/templates/tool_react/jest.config.js +0 -12
  151. data/templates/tool_react/package.json +0 -51
  152. data/templates/tool_react/src/openc3-tool_name.js +0 -24
  153. data/templates/tool_react/src/root.component.js +0 -88
  154. data/templates/tool_react/src/root.component.test.js +0 -9
  155. data/templates/tool_react/webpack.config.js +0 -27
  156. data/templates/tool_svelte/.gitignore +0 -71
  157. data/templates/tool_svelte/.prettierignore +0 -8
  158. data/templates/tool_svelte/.prettierrc.js +0 -5
  159. data/templates/tool_svelte/babel.config.js +0 -12
  160. data/templates/tool_svelte/build/smui.css +0 -1
  161. data/templates/tool_svelte/jest.config.js +0 -9
  162. data/templates/tool_svelte/package.json +0 -49
  163. data/templates/tool_svelte/pnpm-workspace.yaml +0 -20
  164. data/templates/tool_svelte/rollup.config.js +0 -74
  165. data/templates/tool_svelte/src/App.svelte +0 -42
  166. data/templates/tool_svelte/src/App.test.js +0 -9
  167. data/templates/tool_svelte/src/theme/_smui-theme.scss +0 -25
  168. data/templates/tool_svelte/src/tool_name.js +0 -17
  169. data/templates/widget/LICENSE.md +0 -20
@@ -12,16 +12,17 @@
12
12
  # if purchased from OpenC3, Inc.
13
13
 
14
14
  require 'open3'
15
+ require 'json'
15
16
 
16
17
  module OpenC3
17
18
  class CliGenerator
18
- GENERATORS = %w(plugin target microservice widget conversion processor limits_response tool tool_vue tool_angular tool_react tool_svelte command_validator)
19
+ GENERATORS = %w(plugin target microservice widget panel conversion processor limits_response tool tool_vue command_validator)
19
20
  TEMPLATES_DIR = "#{File.dirname(__FILE__)}/../../../templates"
20
21
 
21
22
  # Generators that derive language from the target's target.txt
22
23
  TARGET_DERIVED_GENERATORS = %w(conversion processor limits_response command_validator).freeze
23
24
  # Generators that are JavaScript-only and ignore language flags
24
- JS_ONLY_GENERATORS = %w(widget tool tool_vue tool_angular tool_react tool_svelte).freeze
25
+ JS_ONLY_GENERATORS = %w(widget panel tool tool_vue).freeze
25
26
  # Generators that require an explicit language (or env/plugin default)
26
27
  LANGUAGE_REQUIRED_GENERATORS = %w(target microservice).freeze
27
28
 
@@ -37,15 +38,13 @@ module OpenC3
37
38
  puts " target Create a new target within a plugin (--ruby/--python required or inherited)"
38
39
  puts " microservice Create a new microservice within a plugin (--ruby/--python required or inherited)"
39
40
  puts " widget Create a new custom widget (JavaScript only)"
41
+ puts " panel Create a new custom Dashboards panel (JavaScript only)"
40
42
  puts " conversion Create a new conversion class for a target (language inherited from target)"
41
43
  puts " processor Create a new processor for a target (language inherited from target)"
42
44
  puts " limits_response Create a new limits response for a target (language inherited from target)"
43
45
  puts " command_validator Create a new command validator for a target (language inherited from target)"
44
46
  puts " tool Create a new tool, Vue.js by default (JavaScript only)"
45
47
  puts " tool_vue Create a new Vue.js tool (JavaScript only)"
46
- puts " tool_angular Create a new Angular tool (JavaScript only)"
47
- puts " tool_react Create a new React tool (JavaScript only)"
48
- puts " tool_svelte Create a new Svelte tool (JavaScript only)"
49
48
  puts ""
50
49
  puts "Run 'cli generate GENERATOR --help' for detailed help on each generator."
51
50
  puts ""
@@ -63,6 +62,7 @@ module OpenC3
63
62
  puts " cli generate plugin MyPlugin --ruby # Plugin defaults future generators to Ruby"
64
63
  puts " cli generate target EXAMPLE --python # Or inherit from plugin's stored default"
65
64
  puts " cli generate widget SuperdataWidget # No language flag needed"
65
+ puts " cli generate panel BatteryPanel # Dashboards panel type BATTERY"
66
66
  puts " cli generate conversion EXAMPLE STATUS # Language read from targets/EXAMPLE/target.txt"
67
67
  puts ""
68
68
  puts "Documentation:"
@@ -450,6 +450,35 @@ module OpenC3
450
450
  nil
451
451
  end
452
452
 
453
+ # Give a plugin gaining its first python target a pyproject.toml, the same
454
+ # one `generate plugin --python` writes, plus the lib/ package that its ty
455
+ # extra-paths points at. requirements.txt is deprecated, so it is never
456
+ # created; a legacy one is left in place with a warning rather than
457
+ # converted, because its pins may not survive an automatic move.
458
+ def self.add_python_dependency_file
459
+ return if File.exist?('pyproject.toml')
460
+
461
+ if File.exist?('requirements.txt')
462
+ puts "Warning: requirements.txt is deprecated for plugin python dependencies. " \
463
+ "Move them into pyproject.toml: https://docs.openc3.com/docs/configuration/plugins#phase-2-deploy"
464
+ return
465
+ end
466
+ gemspec_filename = Dir['*.gemspec'][0]
467
+ return unless gemspec_filename
468
+
469
+ plugin_name = File.basename(gemspec_filename, '.gemspec')
470
+ package_name = plugin_name.gsub(/[^a-z0-9]+/, '_')
471
+ pyproject = ERB.new(File.read("#{TEMPLATES_DIR}/plugin/pyproject.toml"), trim_mode: "-").result(binding)
472
+ File.write('pyproject.toml', pyproject)
473
+ init_path = "lib/#{package_name}/__init__.py"
474
+ unless File.exist?(init_path)
475
+ FileUtils.mkdir_p(File.dirname(init_path))
476
+ FileUtils.cp("#{TEMPLATES_DIR}/plugin/lib/PACKAGE/__init__.py", init_path)
477
+ end
478
+ write_python_version
479
+ puts "Created pyproject.toml. Add the plugin's python dependencies to it, then run `uv lock`."
480
+ end
481
+
453
482
  def self.generate_target(args)
454
483
  validate_language_inheriting_args!('target', args,
455
484
  example: ['cli generate target EXAMPLE --ruby', 'Creates: targets/EXAMPLE/'],
@@ -475,13 +504,7 @@ module OpenC3
475
504
  end
476
505
 
477
506
  if @@language == 'py'
478
- # If we're using Python create a requirements.txt and list it in the gemspec
479
- # However, don't write over an existing file they may have already created
480
- unless File.exist?("requirements.txt")
481
- File.open("requirements.txt", 'w') do |file|
482
- file.puts "# Python dependencies"
483
- end
484
- end
507
+ add_python_dependency_file
485
508
  gemspec_filename = Dir['*.gemspec'][0]
486
509
  gemspec = File.read(gemspec_filename)
487
510
  # Older COSMOS versions wrote a singular python_dep_file block that never
@@ -654,6 +677,87 @@ module OpenC3
654
677
  return widget_name
655
678
  end
656
679
 
680
+ def self.generate_panel(args)
681
+ if args[1].nil? || args[1] == '--help' || args[1] == '-h'
682
+ print_help(
683
+ usage: 'cli generate panel NAME',
684
+ description: 'Generate a new custom Dashboards panel type within an existing plugin',
685
+ arguments: [
686
+ 'NAME Name of the panel (required)',
687
+ " Must be CapitalCase ending with 'Panel'",
688
+ ' The panel type is NAME without Panel, uppercased',
689
+ ' Example: BatteryPanel (panel type BATTERY)',
690
+ ],
691
+ notes: 'Note: Panels are JavaScript only. --ruby/--python flags are ignored.',
692
+ example: [
693
+ 'cli generate panel BatteryPanel',
694
+ 'Creates: src/BatteryPanel.js, src/BatteryPanel.vue, vite-BatteryPanel.config.js',
695
+ ],
696
+ docs: 'https://docs.openc3.com/docs/guides/custom-panels',
697
+ exit_code: (args[1].nil? ? 1 : 0),
698
+ )
699
+ end
700
+ if args.length != 2
701
+ abort("Usage: cli generate #{args[0]} <BatteryPanel>")
702
+ end
703
+ if !args[1].end_with?('Panel') or args[1].length <= 5 or args[1][0...-5] != args[1][0...-5].capitalize
704
+ abort("Panel name should be Uppercase followed by Panel, e.g. BatteryPanel. Found '#{args[1]}'.")
705
+ end
706
+
707
+ # Create the local variables, used in binding for the templates
708
+ panel_name = args[1]
709
+ panel_type = panel_name[0...-5].upcase
710
+ panel_label = panel_name[0...-5]
711
+ panel_label.inspect # Remove unused variable warning
712
+ vite_config = "vite-#{panel_name}.config.js"
713
+ ["src/#{panel_name}.js", "src/#{panel_name}.vue", vite_config].each do |path|
714
+ abort("Panel #{path} already exists!") if File.exist?(path)
715
+ end
716
+ if File.exist?('plugin.txt') && File.read('plugin.txt') =~ /^PANEL\s+#{Regexp.escape(panel_type)}\b/
717
+ abort("plugin.txt already declares PANEL #{panel_type}. Remove that entry before regenerating.")
718
+ end
719
+ # A plugin with JavaScript already has its package.json and Rakefile, so
720
+ # only the build step is added
721
+ existing_package = File.exist?('package.json')
722
+
723
+ process_template("#{TEMPLATES_DIR}/panel", binding) do |filename|
724
+ if existing_package && ['package.json', 'Rakefile', 'pnpm-workspace.yaml', '.prettierrc.cjs', 'LICENSE.md'].include?(filename)
725
+ true # causes the block to skip processing this file
726
+ elsif filename == 'src/panelSdk.js' && File.exist?(filename)
727
+ true # shared by every panel in the plugin
728
+ else
729
+ filename.sub!("src/Panel.", "src/#{panel_name}.")
730
+ filename.sub!("vite-Panel.config.js", vite_config)
731
+ false
732
+ end
733
+ end
734
+
735
+ if existing_package
736
+ package = JSON.parse(File.read('package.json'))
737
+ package['scripts'] ||= {}
738
+ build = "vite build -c #{vite_config}"
739
+ package['scripts']['build'] = [package['scripts']['build'], build].compact.reject(&:empty?).join(' && ')
740
+ package['devDependencies'] ||= {}
741
+ { '@vitejs/plugin-vue' => '^6.0.1', 'vite' => '^7.2.1', 'vite-plugin-style-inject' => '^0.0.1', 'vue' => '^3.5.13' }.each do |name, version|
742
+ package['devDependencies'][name] ||= version unless package.dig('dependencies', name)
743
+ end
744
+ File.write('package.json', JSON.pretty_generate(package) + "\n")
745
+ puts "Added '#{build}' to the build script in package.json."
746
+ end
747
+
748
+ # Add this panel to plugin.txt
749
+ File.open("plugin.txt", 'a') do |file|
750
+ file.puts <<~DOC
751
+
752
+ PANEL #{panel_type}
753
+ DOC
754
+ end
755
+
756
+ puts "Panel #{panel_name} successfully generated!"
757
+ puts "Use it in a dashboard as PANEL #{panel_type}. Be sure #{panel_type} does not overlap a built-in panel type: https://docs.openc3.com/docs/guides/custom-panels"
758
+ return panel_name
759
+ end
760
+
657
761
  def self.generate_tool(args)
658
762
  if args[1].nil? || args[1] == '--help' || args[1] == '-h'
659
763
  tool_type = args[0].to_s.downcase.gsub('-', '_')
@@ -665,13 +769,7 @@ module OpenC3
665
769
  docs_url = 'https://docs.openc3.com/docs/guides/custom-tools'
666
770
 
667
771
  if tool_type != 'tool'
668
- framework = case tool_type
669
- when 'tool_vue' then 'Vue.js'
670
- when 'tool_react' then 'React'
671
- when 'tool_angular' then 'Angular'
672
- when 'tool_svelte' then 'Svelte'
673
- else 'Custom'
674
- end
772
+ framework = 'Vue.js'
675
773
  print_help(
676
774
  usage: "cli generate #{args[0]} 'TOOL NAME'",
677
775
  description: "Generate a new #{framework} tool within an existing plugin",
@@ -696,9 +794,6 @@ module OpenC3
696
794
  lines: [
697
795
  'tool Generate Vue.js tool (default)',
698
796
  'tool_vue Generate Vue.js tool',
699
- 'tool_angular Generate Angular tool',
700
- 'tool_react Generate React tool',
701
- 'tool_svelte Generate Svelte tool',
702
797
  ],
703
798
  },
704
799
  example: [
@@ -756,9 +851,6 @@ module OpenC3
756
851
  return tool_name
757
852
  end
758
853
  self.singleton_class.send(:alias_method, :generate_tool_vue, :generate_tool)
759
- self.singleton_class.send(:alias_method, :generate_tool_react, :generate_tool)
760
- self.singleton_class.send(:alias_method, :generate_tool_angular, :generate_tool)
761
- self.singleton_class.send(:alias_method, :generate_tool_svelte, :generate_tool)
762
854
 
763
855
  def self.generate_conversion(args)
764
856
  generate_target_artifact(args, {
@@ -0,0 +1,38 @@
1
+ # encoding: ascii-8bit
2
+
3
+ # Copyright 2026 OpenC3, Inc.
4
+ # All Rights Reserved.
5
+ #
6
+ # This program is distributed in the hope that it will be useful,
7
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
8
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
9
+ # See LICENSE.md for more details.
10
+ #
11
+ # This file may also be used under the terms of a commercial license
12
+ # if purchased from OpenC3, Inc.
13
+
14
+ module OpenC3
15
+ # Rack middleware that removes the Client-IP and Forwarded request headers
16
+ # before Rails computes request.remote_ip.
17
+ #
18
+ # COSMOS runs behind traefik, which sets X-Forwarded-For (and X-Real-Ip) from
19
+ # the real connection. Traefik does not touch Client-IP or Forwarded, so they
20
+ # arrive exactly as the browser sent them, yet ActionDispatch::RemoteIp uses
21
+ # both when picking the client address. Removing them means remote_ip only
22
+ # comes from REMOTE_ADDR and X-Forwarded-For, which traefik controls.
23
+ #
24
+ # Insert before ActionDispatch::RemoteIp:
25
+ # config.middleware.insert_before(ActionDispatch::RemoteIp, OpenC3::ClientIpHeaderFilter)
26
+ class ClientIpHeaderFilter
27
+ HEADERS = %w[HTTP_CLIENT_IP HTTP_FORWARDED].freeze
28
+
29
+ def initialize(app)
30
+ @app = app
31
+ end
32
+
33
+ def call(env)
34
+ HEADERS.each { |header| env.delete(header) }
35
+ @app.call(env)
36
+ end
37
+ end
38
+ end
@@ -28,7 +28,8 @@ module OpenC3
28
28
  #
29
29
  # Every API writer that can reach the overlay must consult these predicates:
30
30
  # - storage_controller#get_upload_presigned_request / delete (presigned S3 upload)
31
- # - tables_controller#save / save_as / report / destroy (Table -> TargetFile)
31
+ # - tables_controller#save / save_as / report / destroy / generate
32
+ # (Table -> TargetFile; script_edit outside the code areas)
32
33
  # - scripts_controller#create / destroy (Script -> TargetFile)
33
34
  module ConfigOverlay
34
35
  # Config bucket areas a non-admin is allowed to write at all
@@ -70,6 +71,28 @@ module OpenC3
70
71
  parts.length > 3 and parts[1, 2] == ['tables', 'config']
71
72
  end
72
73
 
74
+ # True if the given config bucket key is a targets_modified/<TARGET> overlay
75
+ # file whose write requires script_edit rather than only system_set. Script
76
+ # Runner executes these files: procedures and lib are run / required
77
+ # directly, and Script.body / bucket_load will load any overlay path, so
78
+ # every targets_modified target file outside the admin-only code areas
79
+ # (cmd_tlm, tables/config) counts. tmp/ scratch and non-overlay keys return
80
+ # false. Fails closed (false) on non-canonical keys.
81
+ #
82
+ # Callers must still require admin for code areas (code_overlay? /
83
+ # non_admin_writable_key? already fail those), so the tiers are:
84
+ # code area -> admin
85
+ # script_edit area -> script_edit (this predicate)
86
+ # tmp / user bucket -> system_set
87
+ def self.script_edit_overlay_key?(key)
88
+ parts = canonical_parts(key)
89
+ return false if parts.nil?
90
+ # parts: <SCOPE> / <area> / <TARGET> / <subdir> / ...
91
+ return false unless parts[1] == 'targets_modified'
92
+ return false if code_area?(parts[2..])
93
+ true
94
+ end
95
+
73
96
  # True if the given config bucket key is an overlay path a non-admin may
74
97
  # write. Key is the full bucket key, e.g.
75
98
  # "<SCOPE>/targets_modified/<TARGET>/screens/x.txt". Fails closed (false) on
@@ -7,6 +7,23 @@ module OpenC3
7
7
  class CosmosRailsFormatter
8
8
  include OpenC3::Authorization
9
9
 
10
+ # Resolve the username for a request, for use as a config.log_tags entry:
11
+ #
12
+ # formatter = OpenC3::CosmosRailsFormatter.new
13
+ # config.log_tags = { request_id: :request_id, username: ->(request) { formatter.username(request) } }
14
+ #
15
+ # Resolving it here, once per request, keeps the token itself out of the logger.
16
+ # Returns nil (no tag) when the request has no token, or 'anonymous' when the token
17
+ # does not resolve to a username (always in Core, which has no usernames).
18
+ def username(request)
19
+ token = request.headers['HTTP_AUTHORIZATION'] || request.query_parameters[:authorization]
20
+ return nil unless token
21
+
22
+ user_info(token)['username'] || 'anonymous'
23
+ rescue StandardError
24
+ 'anonymous'
25
+ end
26
+
10
27
  def call(log, _appender = nil)
11
28
  #<SemanticLogger::Log:0x0000ffffa5002b20 @level=:info, @thread_name="puma srv tp 001", @name="MicroservicesController",
12
29
  # @time=2024-09-22 18:04:27.955490052 +0000, @tags=[], @named_tags={}, @level_index=2, @message="Completed #traefik",
@@ -22,16 +39,7 @@ module OpenC3
22
39
  username = nil
23
40
  if named_tags
24
41
  other[:request_id] = named_tags[:request_id]
25
- if named_tags[:token]
26
- begin
27
- user = user_info(named_tags[:token])
28
- rescue
29
- user = {}
30
- end
31
- username = user['username']
32
- # Core username (Enterprise has the actual username)
33
- username ||= 'anonymous'
34
- end
42
+ username = named_tags[:username]
35
43
  end
36
44
  username ||= 'anonymous'
37
45
  payload = log.payload
@@ -0,0 +1,279 @@
1
+ # encoding: ascii-8bit
2
+
3
+ # Copyright 2026 OpenC3, Inc.
4
+ # All Rights Reserved.
5
+ #
6
+ # This program is distributed in the hope that it will be useful,
7
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
8
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
9
+ # See LICENSE.md for more details.
10
+ #
11
+ # This file may also be used under the terms of a commercial license
12
+ # if purchased from OpenC3, Inc.
13
+
14
+ require 'json'
15
+ require 'openc3/models/bridge_model'
16
+ require 'openc3/models/gem_model'
17
+ require 'openc3/models/plugin_model'
18
+ require 'openc3/models/plugin_store_model'
19
+ require 'openc3/topics/discovery_topic'
20
+
21
+ module OpenC3
22
+ # Hardware discovery scans the hosts connected through bridges for devices and
23
+ # proposes plugins to install for them. Plugins are matched by the hardware
24
+ # their plugin.txt can discover (PluginModel.discovery_matchers): plugins in
25
+ # the OpenC3 Store, which computes their matchers when they're uploaded, and
26
+ # plugins already installed in COSMOS, which can be installed again for
27
+ # another device.
28
+ module HardwareDiscovery
29
+ # Seconds to wait for a host to scan. Scanning takes about 10s.
30
+ SCAN_TIMEOUT_S = 40
31
+
32
+ # Matchers of installed plugin gems by gem filename. Gem files don't change
33
+ # once uploaded so this only grows with new versions.
34
+ @gem_matchers = {}
35
+ @gem_matchers_mutex = Mutex.new
36
+
37
+ # Scan the host of one bridge, or every paired bridge with 'ALL', and
38
+ # propose plugins for the devices found
39
+ #
40
+ # @return [Hash] 'devices' found with their 'candidates' (plugins to
41
+ # install), 'errors' scanning, the number of matchers 'skipped' and
42
+ # whether the OpenC3 Store provided any matchers ('store_matchers')
43
+ def self.scan(bridge: 'DEFAULT', scope:)
44
+ sources = plugin_sources(scope: scope)
45
+ matchers, candidates_by_id = unique_matchers(sources)
46
+ bridges = bridge_names(bridge, scope: scope)
47
+ if bridges.empty?
48
+ raise "No bridge is paired with openc3-cosmos-app" if bridge.to_s.upcase == 'ALL'
49
+ raise "Bridge '#{bridge.to_s.upcase}' is not paired with openc3-cosmos-app"
50
+ end
51
+
52
+ results = {}
53
+ bridges.map do |bridge_name|
54
+ Thread.new do
55
+ results[bridge_name] = DiscoveryTopic.scan(bridge_name, { 'matchers' => matchers }, timeout: SCAN_TIMEOUT_S, scope: scope)
56
+ rescue => error
57
+ results[bridge_name] = { 'error' => error.message }
58
+ end
59
+ end.each(&:join)
60
+
61
+ devices = []
62
+ errors = []
63
+ skipped = 0
64
+ bridges.each do |bridge_name|
65
+ result = results[bridge_name]
66
+ if result['error']
67
+ errors << { 'bridge' => bridge_name, 'message' => result['error'] }
68
+ next
69
+ end
70
+ (result['errors'] || {}).each do |discovery_class, message|
71
+ errors << { 'bridge' => bridge_name, 'class' => discovery_class, 'message' => message }
72
+ end
73
+ skipped += (result['skipped'] || {}).length
74
+ claims = Hash.new do |hash, discovery_class|
75
+ hash[discovery_class] = PluginModel.discovery_claims(bridge_name, discovery_class, scope: scope)
76
+ end
77
+ (result['devices'] || []).each do |device|
78
+ devices << device_proposal(bridge_name, device, candidates_by_id, claims)
79
+ end
80
+ end
81
+ {
82
+ 'devices' => devices,
83
+ 'errors' => errors,
84
+ 'skipped' => skipped,
85
+ 'store_matchers' => sources.any? { |source| source['source'] == 'store' and !source['matchers'].empty? },
86
+ }
87
+ end
88
+
89
+ # The plugins that can be proposed, each with its matchers: OpenC3 Store
90
+ # plugins with discovery data, then installed plugins not already offered
91
+ # by the store
92
+ def self.plugin_sources(scope:)
93
+ installed = PluginModel.all(scope: scope)
94
+ installed_gems = installed.keys.map { |name| name.split('__')[0] }.uniq
95
+ installed_names = installed_gems.map { |gem| gem_name(gem) }
96
+ installed_store_ids = installed.values.map { |plugin| plugin['store_plugin_id'] }.compact
97
+
98
+ sources = []
99
+ store_plugins.each do |plugin|
100
+ matchers = store_matchers(plugin)
101
+ next if matchers.empty?
102
+ name = gem_name(plugin['gem_filename'].to_s)
103
+ sources << {
104
+ 'source' => 'store',
105
+ 'store_id' => plugin['id'],
106
+ 'store_version_id' => plugin['current_version_id'],
107
+ 'name' => name,
108
+ 'title' => plugin['title'],
109
+ 'image_url' => plugin['image_url'],
110
+ 'entitled' => plugin.fetch('entitled', true) != false,
111
+ 'installed' => installed_store_ids.include?(plugin['id']) || installed_names.include?(name),
112
+ 'matchers' => matchers,
113
+ }
114
+ end
115
+ store_names = sources.map { |source| source['name'] }
116
+ installed_gems.each do |gem|
117
+ next if store_names.include?(gem_name(gem))
118
+ matchers = gem_discovery_matchers(gem, scope: scope)
119
+ next if matchers.empty?
120
+ sources << {
121
+ 'source' => 'installed',
122
+ 'gem' => gem,
123
+ 'name' => gem_name(gem),
124
+ 'title' => gem_name(gem),
125
+ 'entitled' => true,
126
+ 'installed' => true,
127
+ 'matchers' => matchers,
128
+ }
129
+ end
130
+ sources
131
+ end
132
+
133
+ # The OpenC3 Store catalog, or none if it can't be read
134
+ def self.store_plugins
135
+ plugins = JSON.parse(PluginStoreModel.all || '[]')
136
+ plugins.is_a?(Array) ? plugins : []
137
+ rescue JSON::ParserError
138
+ []
139
+ end
140
+
141
+ # The matchers the Store computed for a plugin, if they're in a format this
142
+ # COSMOS understands. The Store bumps the format when matchers change
143
+ # meaning, which older COSMOS versions must not guess at.
144
+ def self.store_matchers(plugin)
145
+ discovery = plugin['discovery']
146
+ return [] unless discovery.is_a?(Hash) and discovery['format'] == PluginModel::DISCOVERY_MATCHERS_FORMAT
147
+
148
+ Array(discovery['matchers']).select { |matcher| matcher.is_a?(Hash) and matcher['class'].is_a?(String) and matcher['variable'].is_a?(String) }
149
+ end
150
+
151
+ # The matchers of an installed plugin gem, from its plugin.txt
152
+ def self.gem_discovery_matchers(gem, scope:)
153
+ @gem_matchers_mutex.synchronize do
154
+ return @gem_matchers[gem] if @gem_matchers.key?(gem)
155
+ variables = PluginModel.install_phase1(GemModel.get(gem), validate_only: true, scope: scope)['variables']
156
+ # plugin.txt is read as binary but its titles are UTF-8 text, as the store's are
157
+ # Only successful reads are cached so a failure is retried on the next scan
158
+ @gem_matchers[gem] = utf8(PluginModel.discovery_matchers(variables)['matchers'])
159
+ rescue => error
160
+ Logger.warn("Hardware discovery could not read the plugin.txt of #{gem}: #{error.message}", scope: scope)
161
+ []
162
+ end
163
+ end
164
+
165
+ # Each distinct discovery (class and parameters) is checked once on the
166
+ # host, though many plugins may use it. Returns the matchers to send and
167
+ # the plugin candidates for each matcher id.
168
+ def self.unique_matchers(sources)
169
+ ids = {}
170
+ candidates_by_id = Hash.new { |hash, id| hash[id] = [] }
171
+ sources.each do |source|
172
+ source['matchers'].each do |matcher|
173
+ key = [PluginModel.discovery_class_key(matcher['class']), Array(matcher['params'])]
174
+ id = (ids[key] ||= (ids.length + 1).to_s)
175
+ candidates_by_id[id] << [source, matcher]
176
+ end
177
+ end
178
+ matchers = ids.map { |(discovery_class, params), id| { 'id' => id, 'class' => discovery_class, 'params' => params } }
179
+ [matchers, candidates_by_id]
180
+ end
181
+
182
+ def self.bridge_names(bridge, scope:)
183
+ bridge = bridge.to_s.upcase
184
+ paired = BridgeModel.all(scope: scope).select { |_name, model| model['app_public_key'] }.keys.sort
185
+ return paired if bridge == 'ALL'
186
+ paired.include?(bridge) ? [bridge] : []
187
+ end
188
+
189
+ # A device found on a host with the plugins proposed for it, most specific
190
+ # match first
191
+ def self.device_proposal(bridge_name, device, candidates_by_id, claims)
192
+ discovery_class = device['class']
193
+ matched_params = Hash(device['matched_params'])
194
+ candidates = Array(device['matches']).flat_map do |id|
195
+ candidates_by_id[id].map do |source, matcher|
196
+ variables = Hash(matcher['set']).merge(matcher['variable'] => device['value'], PluginModel::BRIDGE_VARIABLE_NAME => bridge_name)
197
+ candidate = source.slice('source', 'store_id', 'store_version_id', 'gem', 'name', 'title', 'image_url', 'entitled', 'installed').compact
198
+ # Rated by the parameters the device matched when the host says
199
+ # which (a matcher's parameters are usually alternatives)
200
+ params = Array(matcher['params'])
201
+ indexes = matched_params[id.to_s]
202
+ params = params.values_at(*indexes).compact if indexes.is_a?(Array) and !indexes.empty?
203
+ candidate.merge(
204
+ 'match_title' => matcher['title'],
205
+ 'variables' => variables,
206
+ 'specificity' => specificity(discovery_class, params),
207
+ 'possible' => name_pattern_only?(discovery_class, params),
208
+ )
209
+ end
210
+ end
211
+ # A plugin matched more than once for the device keeps its best match,
212
+ # and matches by a name pattern alone come after the others
213
+ candidates = candidates.sort_by { |candidate| [candidate['possible'] ? 1 : 0, -candidate['specificity'], candidate['title'].to_s.downcase] }
214
+ candidates = candidates.uniq { |candidate| [candidate['source'], candidate['name'], candidate['match_title'], candidate['variables']] }
215
+ {
216
+ 'bridge' => bridge_name,
217
+ 'class' => discovery_class,
218
+ 'value' => device['value'],
219
+ 'text' => device['text'],
220
+ 'details' => device['details'] || {},
221
+ 'claimed_by' => claims[discovery_class][device['value'].to_s],
222
+ 'candidates' => candidates,
223
+ }
224
+ end
225
+
226
+ # How specifically a matcher identifies hardware, so an exact USB product
227
+ # ranks above a USB serial chip many devices use
228
+ def self.specificity(discovery_class, params)
229
+ case discovery_class.split('.').last
230
+ when 'serial_discovery'
231
+ params.map { |param| param =~ /:[0-9A-Fa-f]+\z/ ? 2 : 1 }.max || 0
232
+ when 'hid_discovery'
233
+ params.count { |param| !%w(0 0x0 nil none).include?(param.to_s.strip.downcase) && !param.to_s.strip.empty? }
234
+ when 'usb_discovery'
235
+ # |-separated conditions where a VID:PID is two (vendor and product)
236
+ params.map { |param| param.split('|').sum { |condition| condition =~ /\A\h+:\h+\z/ ? 2 : 1 } }.max || 0
237
+ else
238
+ # zeroconf, bluetooth, ssdp and neighbor matchers are |-separated conditions
239
+ params.map { |param| param.split('|').length }.max || 0
240
+ end
241
+ end
242
+
243
+ # The conditions that only match a device's name, by discovery class
244
+ NAME_CONDITIONS = {
245
+ 'bluetooth_discovery' => %w(local_name),
246
+ 'neighbor_discovery' => %w(hostname),
247
+ 'usb_discovery' => %w(manufacturer product),
248
+ 'ssdp_discovery' => %w(friendlyname),
249
+ }
250
+
251
+ # Whether a match is only by a name pattern (e.g. a Bluetooth local_name of
252
+ # Govee*), which other devices from the same maker can share, so the plugin
253
+ # may not support the device
254
+ def self.name_pattern_only?(discovery_class, params)
255
+ keys = NAME_CONDITIONS[discovery_class.to_s.split('.').last]
256
+ return false if keys.nil? or params.empty?
257
+ params.all? do |param|
258
+ param.to_s.split('|').all? do |condition|
259
+ key, glob = condition.split('=', 2)
260
+ keys.include?(key.to_s.strip.downcase) and glob.to_s.match?(/[*?\[]/)
261
+ end
262
+ end
263
+ end
264
+
265
+ def self.utf8(value)
266
+ case value
267
+ when String then value.dup.force_encoding('UTF-8')
268
+ when Array then value.map { |item| utf8(item) }
269
+ when Hash then value.to_h { |key, item| [utf8(key), utf8(item)] }
270
+ else value
271
+ end
272
+ end
273
+
274
+ # A gem's name without its version, e.g. openc3-cosmos-demo
275
+ def self.gem_name(gem_filename)
276
+ File.basename(gem_filename.to_s, '.gem').sub(/-\d[\w.]*\z/, '')
277
+ end
278
+ end
279
+ end