bro_hub 0.2.0 → 0.3.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 (147) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +21 -0
  3. data/README.md +175 -165
  4. data/app/controllers/bro_hub/apm/application_controller.rb +26 -0
  5. data/app/controllers/bro_hub/apm/deploys_controller.rb +7 -0
  6. data/app/controllers/bro_hub/apm/endpoints_controller.rb +8 -0
  7. data/app/controllers/bro_hub/apm/errors_controller.rb +15 -0
  8. data/app/controllers/bro_hub/apm/findings_controller.rb +8 -0
  9. data/app/controllers/bro_hub/apm/overview_controller.rb +7 -0
  10. data/app/controllers/bro_hub/apm/queries_controller.rb +11 -0
  11. data/app/controllers/bro_hub/apm/status_controller.rb +9 -0
  12. data/app/controllers/bro_hub/application_controller.rb +16 -0
  13. data/app/controllers/bro_hub/audit_events_controller.rb +2 -2
  14. data/app/controllers/bro_hub/cache/application_controller.rb +55 -0
  15. data/app/controllers/bro_hub/cache/audit_events_controller.rb +40 -0
  16. data/app/controllers/bro_hub/cache/flushes_controller.rb +34 -0
  17. data/app/controllers/bro_hub/cache/keys_controller.rb +41 -0
  18. data/app/controllers/bro_hub/cache/purges_controller.rb +40 -0
  19. data/app/controllers/bro_hub/env/application_controller.rb +27 -0
  20. data/app/controllers/bro_hub/env/audit_controller.rb +10 -0
  21. data/app/controllers/bro_hub/env/home_controller.rb +6 -0
  22. data/app/controllers/bro_hub/env/proposals_controller.rb +86 -0
  23. data/app/controllers/bro_hub/env/reviews_controller.rb +72 -0
  24. data/app/controllers/bro_hub/feature_controller.rb +21 -0
  25. data/app/controllers/bro_hub/safe/application_controller.rb +24 -0
  26. data/app/controllers/bro_hub/safe/flagged_commands_controller.rb +14 -0
  27. data/app/controllers/bro_hub/safe/reviews_controller.rb +39 -0
  28. data/app/controllers/bro_hub/safe/rules_controller.rb +18 -0
  29. data/app/controllers/bro_hub/safe/sessions_controller.rb +63 -0
  30. data/app/controllers/bro_hub/safe/unlocks_controller.rb +14 -0
  31. data/app/helpers/bro_hub/apm/application_helper.rb +104 -0
  32. data/app/helpers/bro_hub/application_helper.rb +5 -19
  33. data/app/helpers/bro_hub/cache/application_helper.rb +63 -0
  34. data/app/helpers/bro_hub/env/application_helper.rb +67 -0
  35. data/app/helpers/bro_hub/safe/application_helper.rb +59 -0
  36. data/app/jobs/bro_hub/safe/purge_job.rb +10 -0
  37. data/app/models/bro_hub/audit_event.rb +2 -6
  38. data/app/models/bro_hub/cache/audit_event.rb +15 -0
  39. data/app/models/bro_hub/env/audit_event.rb +72 -0
  40. data/app/models/bro_hub/safe/command.rb +22 -0
  41. data/app/models/bro_hub/safe/review.rb +22 -0
  42. data/app/models/bro_hub/safe/session.rb +57 -0
  43. data/app/models/bro_hub/safe/unlock.rb +15 -0
  44. data/app/views/bro_hub/apm/deploys/index.html.erb +21 -0
  45. data/app/views/bro_hub/apm/endpoints/index.html.erb +27 -0
  46. data/app/views/bro_hub/apm/errors/index.html.erb +22 -0
  47. data/app/views/bro_hub/apm/errors/not_found.html.erb +3 -0
  48. data/app/views/bro_hub/apm/errors/show.html.erb +43 -0
  49. data/app/views/bro_hub/apm/findings/index.html.erb +24 -0
  50. data/app/views/bro_hub/apm/overview/show.html.erb +59 -0
  51. data/app/views/bro_hub/apm/queries/index.html.erb +37 -0
  52. data/app/views/bro_hub/apm/shared/_page_styles.html.erb +15 -0
  53. data/app/views/bro_hub/apm/status/show.html.erb +47 -0
  54. data/app/views/bro_hub/audit_events/index.html.erb +1 -1
  55. data/app/views/bro_hub/cache/audit_events/index.html.erb +39 -0
  56. data/app/views/bro_hub/cache/audit_events/show.html.erb +48 -0
  57. data/app/views/bro_hub/cache/flushes/new.html.erb +19 -0
  58. data/app/views/bro_hub/cache/keys/index.html.erb +36 -0
  59. data/app/views/bro_hub/cache/keys/show.html.erb +57 -0
  60. data/app/views/bro_hub/cache/purges/new.html.erb +17 -0
  61. data/app/views/bro_hub/cache/purges/preview.html.erb +37 -0
  62. data/app/views/bro_hub/cache/shared/_store_tabs.html.erb +9 -0
  63. data/app/views/bro_hub/cache/shared/unsupported.html.erb +3 -0
  64. data/app/views/bro_hub/env/audit/index.html.erb +31 -0
  65. data/app/views/bro_hub/env/home/index.html.erb +25 -0
  66. data/app/views/bro_hub/env/proposals/_new_key_row.html.erb +7 -0
  67. data/app/views/bro_hub/env/proposals/new.html.erb +99 -0
  68. data/app/views/bro_hub/env/reviews/new.html.erb +29 -0
  69. data/app/views/bro_hub/env/reviews/show.html.erb +122 -0
  70. data/app/views/bro_hub/env/shared/_page_styles.html.erb +57 -0
  71. data/app/views/bro_hub/env/shared/_script.html.erb +114 -0
  72. data/app/views/bro_hub/env/shared/not_ready.html.erb +17 -0
  73. data/app/views/bro_hub/safe/flagged_commands/index.html.erb +22 -0
  74. data/app/views/bro_hub/safe/rules/show.html.erb +59 -0
  75. data/app/views/bro_hub/safe/sessions/index.html.erb +51 -0
  76. data/app/views/bro_hub/safe/sessions/show.html.erb +92 -0
  77. data/app/views/bro_hub/safe/unlocks/index.html.erb +25 -0
  78. data/app/views/bro_hub/shared/schema_missing.html.erb +25 -0
  79. data/app/views/layouts/bro_hub/application.html.erb +1 -1
  80. data/config/routes/apm.rb +10 -0
  81. data/config/routes/cache.rb +17 -0
  82. data/config/routes/env.rb +10 -0
  83. data/config/routes/safe.rb +10 -0
  84. data/config/routes.rb +9 -4
  85. data/db/migrate/20261129000000_create_bro_hub_tables.rb +85 -0
  86. data/lib/bro_hub/apm/api.rb +88 -0
  87. data/lib/bro_hub/apm/configuration.rb +58 -0
  88. data/lib/bro_hub/apm/local_status.rb +49 -0
  89. data/lib/bro_hub/apm.rb +28 -0
  90. data/lib/bro_hub/audit.rb +2 -9
  91. data/lib/bro_hub/cache/audit.rb +15 -0
  92. data/lib/bro_hub/cache/configuration.rb +105 -0
  93. data/lib/bro_hub/cache/errors.rb +26 -0
  94. data/lib/bro_hub/cache/redis_store.rb +220 -0
  95. data/lib/bro_hub/cache.rb +38 -0
  96. data/lib/bro_hub/configuration.rb +19 -4
  97. data/lib/bro_hub/controller_base.rb +3 -6
  98. data/lib/bro_hub/engine.rb +60 -1
  99. data/lib/bro_hub/env/audit.rb +17 -0
  100. data/lib/bro_hub/env/configuration.rb +72 -0
  101. data/lib/bro_hub/env/credentials.rb +135 -0
  102. data/lib/bro_hub/env/deployments.rb +45 -0
  103. data/lib/bro_hub/env/differ.rb +58 -0
  104. data/lib/bro_hub/env/editor.rb +104 -0
  105. data/lib/bro_hub/env/encrypted_blob.rb +18 -0
  106. data/lib/bro_hub/env/environment.rb +74 -0
  107. data/lib/bro_hub/env.rb +36 -0
  108. data/lib/bro_hub/features.rb +13 -0
  109. data/lib/bro_hub/layout.rb +2 -5
  110. data/lib/bro_hub/safe/cipher.rb +46 -0
  111. data/lib/bro_hub/safe/commands.rb +25 -0
  112. data/lib/bro_hub/safe/configuration.rb +191 -0
  113. data/lib/bro_hub/safe/encrypted_type.rb +16 -0
  114. data/lib/bro_hub/safe/errors.rb +48 -0
  115. data/lib/bro_hub/safe/executor.rb +142 -0
  116. data/lib/bro_hub/safe/guards/const_guard.rb +42 -0
  117. data/lib/bro_hub/safe/guards/credentials_guard.rb +31 -0
  118. data/lib/bro_hub/safe/guards/env_guard.rb +90 -0
  119. data/lib/bro_hub/safe/guards/file_guard.rb +28 -0
  120. data/lib/bro_hub/safe/guards/guarded.rb +51 -0
  121. data/lib/bro_hub/safe/guards/irb_context.rb +23 -0
  122. data/lib/bro_hub/safe/guards/method_guard.rb +32 -0
  123. data/lib/bro_hub/safe/guards/network_guard.rb +98 -0
  124. data/lib/bro_hub/safe/guards/sql_guard.rb +26 -0
  125. data/lib/bro_hub/safe/parsed_command.rb +66 -0
  126. data/lib/bro_hub/safe/recorder.rb +82 -0
  127. data/lib/bro_hub/safe/shield.rb +83 -0
  128. data/lib/bro_hub/safe/supervisor.rb +81 -0
  129. data/lib/bro_hub/safe/terminal.rb +55 -0
  130. data/lib/bro_hub/safe/trail.rb +24 -0
  131. data/lib/bro_hub/safe/validator.rb +74 -0
  132. data/lib/bro_hub/safe.rb +134 -0
  133. data/lib/bro_hub/schema.rb +36 -0
  134. data/lib/bro_hub/section.rb +7 -13
  135. data/lib/bro_hub/testing.rb +23 -6
  136. data/lib/bro_hub/version.rb +1 -1
  137. data/lib/bro_hub.rb +31 -6
  138. data/lib/generators/bro_hub/install/install_generator.rb +89 -71
  139. data/lib/generators/bro_hub/install/templates/bro_hub.rb.tt +115 -0
  140. data/lib/generators/bro_hub/uninstall/templates/drop_bro_hub_tables.rb.tt +16 -0
  141. data/lib/generators/bro_hub/uninstall/uninstall_generator.rb +57 -0
  142. data/lib/tasks/bro_hub.rake +9 -0
  143. metadata +148 -13
  144. data/db/migrate/20261116000000_create_bro_hub_audit_events.rb +0 -35
  145. data/lib/bro_hub/root_middleware.rb +0 -17
  146. data/lib/generators/bro_hub/install/templates/bro_hub.rb +0 -11
  147. data/lib/generators/bro_hub/installable.rb +0 -63
@@ -0,0 +1,134 @@
1
+ require "irb"
2
+ require "reline"
3
+ require "set"
4
+ require "socket"
5
+
6
+ module BroHub
7
+ # The safe feature (was SafeBro): audited, guarded Rails console access.
8
+ #
9
+ # * Every console session is recorded: who, why, and every command (encrypted at rest).
10
+ # * Sensitive data (encrypted attributes, credentials, ENV secrets, protected systems) is
11
+ # locked until the person runs unlock! and explains why. Everything done while unlocked
12
+ # is linked to that justification.
13
+ # * Commands are checked before they run: forbidden ones are blocked, suspicious ones flagged.
14
+ # * The audit trail is guarded from what's typed at the console (not tamper-proof: see the README).
15
+ # * Reviewers go through sessions in the hub, under <mount>/safe.
16
+ #
17
+ # Access from the console is a deterrent plus an audit trail, not a sandbox. See the README.
18
+ module Safe
19
+ # The sidebar items of this feature's section, relative to <mount>/safe.
20
+ SIDEBAR_ITEMS = [
21
+ { label: "Sessions", path: "/", match: %r{\A/(sessions(/|\z)|\z)}, badge: -> { BroHub::Safe::Session.review_pending.count } },
22
+ { label: "Flagged commands", path: "/flagged" },
23
+ { label: "Unlocks", path: "/unlocks" },
24
+ { label: "Rules", path: "/rules" }
25
+ ].freeze
26
+
27
+ class << self
28
+ attr_accessor :debug
29
+
30
+ def config
31
+ BroHub.config.safe
32
+ end
33
+
34
+ def enabled?
35
+ config.enabled?
36
+ end
37
+
38
+ # The collaborators are created on first use and then shared.
39
+ def supervisor = @supervisor ||= Supervisor.new
40
+ def shield = @shield ||= Shield.new
41
+ def executor = @executor ||= Executor.new
42
+ def recorder = @recorder ||= Recorder.new
43
+ def validator = @validator ||= Validator.new(config)
44
+
45
+ # For code that exposes sensitive things (e.g. a credentials reveal): call this first.
46
+ # Raises ProtectedResource when running under a console command while the resource is
47
+ # locked. With `locations:` (caller_locations) it only raises for calls made directly
48
+ # from what the person typed.
49
+ def guard!(resource, detail = nil, locations: nil)
50
+ return unless executor.executing_user_command? && shield.protects?(resource)
51
+ return if locations && !executor.from_console?(locations)
52
+
53
+ stop!(ProtectedResource.new(resource, detail))
54
+ end
55
+
56
+ # Raises the error after flagging the command being run, so a command that rescues it is still flagged.
57
+ def stop!(error)
58
+ executor.report(error)
59
+ raise error
60
+ end
61
+
62
+ # Is this one of BroHub's own objects (a class or module, a guard, the configuration or a value in it)?
63
+ # Changing one from the console is tampering.
64
+ def protected_object?(object)
65
+ object = object.attached_object if object.is_a?(Class) && object.singleton_class?
66
+ owner = object.is_a?(Module) ? object : object.class
67
+ owner.name.to_s.start_with?("BroHub") || Guards.built.any? { |guard| guard.equal?(object) } ||
68
+ config.protected_values.any? { |value| value.equal?(object) }
69
+ end
70
+
71
+ # Subscribe with ActiveSupport::Notifications.subscribe(/\.bro_hub_safe\z/) to alert people.
72
+ # Events: session_started, unlocked, command_flagged, session_flagged.
73
+ def notify(event, **payload)
74
+ ActiveSupport::Notifications.instrument("#{event}.bro_hub_safe", payload)
75
+ rescue => error
76
+ Rails.logger&.error("BroHub::Safe: notification #{event} failed: #{error.class}: #{error.message}")
77
+ end
78
+
79
+ # Freezes the configuration, this feature's own classes, this module and BroHub itself so they can't be
80
+ # monkey patched, or have a collaborator swapped for a fake, from a console. BroHub can be reached without
81
+ # typing its name (Rails::Engine.subclasses...module_parent), so freezing only the classes isn't enough.
82
+ #
83
+ # A frozen module can't take new constants or instance variables, so everything is loaded and built first:
84
+ # consoles don't eager load, and an autoload into a frozen namespace fails.
85
+ # Once frozen, reload! and BroHub::Safe.debug= don't work in that console (freeze_internals: false turns it off).
86
+ def lock_down!
87
+ load_everything_before_freezing
88
+ config.lock_down!
89
+ # Every module prepended into Ruby, Rails or IRB too: otherwise remove_method on one takes the guard out.
90
+ [ Executor, Shield, Recorder, Supervisor, Validator, Validator::Validation, *Validator::VALIDATIONS,
91
+ ParsedCommand, Terminal, Commands::Unlock, Commands::Lock, Guards::Guarded, Guards::SqlGuard,
92
+ Guards::EnvGuard, Guards::EnvGuard::Guard, Guards::FileGuard, Guards::MethodGuard, Guards::ConstGuard,
93
+ Guards::ConstGuard::Lookup, Guards::ConstGuard::StringLookup, Guards::CredentialsGuard,
94
+ Guards::CredentialsGuard::Inspect, Guards::IrbContext, Guards::NetworkGuard, Guards::NetworkGuard::Connect,
95
+ Guards::NetworkGuard::Writes, Guards::NetworkGuard::SocketConnect, Cipher, Cipher::Raw,
96
+ *Guards.built, Guards.built, Guards ].each(&:freeze)
97
+ [ BroHub.config.env, BroHub.config.cache, BroHub.config.apm, BroHub.config, self, BroHub ].each(&:freeze)
98
+ end
99
+
100
+ private
101
+ def load_everything_before_freezing
102
+ Rails.autoloaders.main.eager_load_namespace(BroHub) if defined?(Rails) && Rails.respond_to?(:autoloaders)
103
+ %i[ supervisor shield executor recorder validator ].each { |name| public_send(name) }
104
+ # Memoized now: their modules are frozen below.
105
+ Guards::NetworkGuard.send(:targets)
106
+ Cipher.send(:encryptor) if defined?(Rails) && Rails.application
107
+ %i[ safe env cache apm ].each { |key| BroHub.config.public_send(key) }
108
+ %i[ registry skull_data_uri styles ].each { |name| BroHub.public_send(name) }
109
+ end
110
+ end
111
+ end
112
+ end
113
+
114
+ require "bro_hub/safe/errors"
115
+ require "bro_hub/safe/configuration"
116
+ require "bro_hub/safe/cipher"
117
+ require "bro_hub/safe/parsed_command"
118
+ require "bro_hub/safe/validator"
119
+ require "bro_hub/safe/terminal"
120
+ require "bro_hub/safe/trail"
121
+ require "bro_hub/safe/recorder"
122
+ require "bro_hub/safe/executor"
123
+ require "bro_hub/safe/guards/guarded"
124
+ require "bro_hub/safe/guards/sql_guard"
125
+ require "bro_hub/safe/guards/network_guard"
126
+ require "bro_hub/safe/guards/credentials_guard"
127
+ require "bro_hub/safe/guards/env_guard"
128
+ require "bro_hub/safe/guards/file_guard"
129
+ require "bro_hub/safe/guards/method_guard"
130
+ require "bro_hub/safe/guards/const_guard"
131
+ require "bro_hub/safe/guards/irb_context"
132
+ require "bro_hub/safe/commands"
133
+ require "bro_hub/safe/shield"
134
+ require "bro_hub/safe/supervisor"
@@ -0,0 +1,36 @@
1
+ module BroHub
2
+ # Checks that the migration has run (and is not behind this version of the gem), so a hub page can say
3
+ # "run db:migrate" instead of failing with an error page.
4
+ module Schema
5
+ # The gem's migration, by absolute path, so a host app's migration can load it without BroHub::Testing.
6
+ MIGRATION = File.expand_path("../../db/migrate/20261129000000_create_bro_hub_tables.rb", __dir__)
7
+
8
+ EXPECTED = {
9
+ "bro_hub_audit_events" => %w[id source event user_label environment context target count reason ip reference digest
10
+ parent_id details created_at],
11
+ "bro_hub_console_sessions" => %w[id username reason source hostname pid client_ip review_status started_at ended_at
12
+ created_at updated_at],
13
+ "bro_hub_console_unlocks" => %w[id session_id resources justification started_at ended_at created_at updated_at],
14
+ "bro_hub_console_commands" => %w[id session_id unlock_id statements status flag_reason created_at updated_at],
15
+ "bro_hub_console_reviews" => %w[id session_id reviewer status notes created_at updated_at]
16
+ }.freeze
17
+
18
+ module_function
19
+
20
+ # "table" for a missing table, "table.column" for a missing column. Empty when the schema is complete.
21
+ def missing
22
+ connection = ActiveRecord::Base.connection
23
+ EXPECTED.flat_map do |table, columns|
24
+ next [ table ] unless connection.table_exists?(table)
25
+
26
+ (columns - connection.columns(table).map(&:name)).map { |column| "#{table}.#{column}" }
27
+ end
28
+ rescue ActiveRecord::ActiveRecordError
29
+ [ "database unavailable" ]
30
+ end
31
+
32
+ def ready?
33
+ missing.empty?
34
+ end
35
+ end
36
+ end
@@ -1,5 +1,5 @@
1
1
  module BroHub
2
- # One block of the sidebar, owned by one gem.
2
+ # One block of the sidebar: one per enabled feature.
3
3
  class Section
4
4
  ACCENTS = {
5
5
  red: "#f04f54", green: "#2ecc7a", violet: "#7c6dfa", amber: "#f5b84a", blue: "#4aa8f5"
@@ -39,25 +39,23 @@ module BroHub
39
39
 
40
40
  attr_reader :key, :name, :label, :accent, :items, :order
41
41
 
42
- # key: :safe_bro. Also the URL segment the engine is mounted under.
42
+ # key: :safe. Also the URL segment the feature lives under (<mount>/safe).
43
43
  # name: short name for the breadcrumb ("SafeBro"). Defaults to the label up to the first "·".
44
44
  # label: sidebar heading ("SafeBro · audit").
45
45
  # accent: :red, :green, :violet, :amber, :blue, or a hex colour.
46
- # engine: the Rails engine (class or class name) BroHub mounts under /<key>. Leave out if the host mounts it.
47
46
  # items: [ { label:, path:, badge: (callable), match: (Regexp on the section-relative path),
48
47
  # visible_to: ->(user) { true } } ]
49
48
  # visible_to: ->(user) { true } decides whether this person sees the section. Navigation only, not security:
50
- # every engine still authorizes its own pages.
51
- # audit_visible_to: ->(user) { true } decides who may see this gem's rows in the hub's audit log. Leave it out
52
- # when the gem keeps no audit trail: nothing of it shows there. Like everything else here it is a
53
- # filter on what is listed, so the gem should check the same thing on its own audit pages.
49
+ # every feature controller still authorizes its own pages.
50
+ # audit_visible_to: ->(user) { true } decides who may see this feature's rows in the hub's audit log. Leave it
51
+ # out when the feature keeps no audit trail: nothing of it shows there. Like everything else here it
52
+ # is a filter on what is listed, so the feature checks the same thing on its own audit pages.
54
53
  # order: lower comes first.
55
- def initialize(key, label:, items:, name: nil, accent: :violet, engine: nil, visible_to: nil, audit_visible_to: nil, order: 100)
54
+ def initialize(key, label:, items:, name: nil, accent: :violet, visible_to: nil, audit_visible_to: nil, order: 100)
56
55
  @key = key.to_sym
57
56
  @label = label.to_s
58
57
  @name = (name || @label.split("·").first).to_s.strip
59
58
  @accent = resolve_accent(accent)
60
- @engine = engine
61
59
  @visible_to = visible_to
62
60
  @audit_visible_to = audit_visible_to
63
61
  @order = order
@@ -65,10 +63,6 @@ module BroHub
65
63
  raise ArgumentError, "BroHub section #{key} needs at least one item" if @items.empty?
66
64
  end
67
65
 
68
- def engine
69
- @engine.is_a?(String) ? @engine.constantize : @engine
70
- end
71
-
72
66
  def visible_to?(user)
73
67
  return false unless user
74
68
 
@@ -1,13 +1,13 @@
1
1
  require "bro_hub"
2
2
 
3
3
  module BroHub
4
- # For the test suites of Bro gems (and apps): creates the audit table in the test database.
4
+ # For host apps' test suites: creates BroHub's tables in the test database.
5
5
  #
6
6
  # # test_helper.rb, after loading the Rails environment
7
7
  # require "bro_hub/testing"
8
8
  # BroHub::Testing.load_schema
9
9
  module Testing
10
- MIGRATION = File.expand_path("../../db/migrate/20261116000000_create_bro_hub_audit_events.rb", __dir__)
10
+ MIGRATION = BroHub::Schema::MIGRATION
11
11
 
12
12
  # What BroHub's installer would have run (`rails_command`), once record_rails_commands is on.
13
13
  RAILS_COMMANDS = []
@@ -29,14 +29,31 @@ module BroHub
29
29
  RAILS_COMMANDS
30
30
  end
31
31
 
32
- # Always rebuilds the table, so a stale one from an older version can't linger.
32
+ # Turns the given features on for the block, redrawing routes and the sidebar, then puts the previous
33
+ # setting back.
34
+ def with_features(*keys)
35
+ previous = BroHub.config.features
36
+ BroHub.config.features = keys.flatten
37
+ BroHub.register_feature_sections!
38
+ Rails.application.reload_routes!
39
+ yield
40
+ ensure
41
+ BroHub.config.features = previous
42
+ BroHub.register_feature_sections!
43
+ Rails.application.reload_routes!
44
+ end
45
+
46
+ TABLES = %i[bro_hub_console_reviews bro_hub_console_commands bro_hub_console_unlocks bro_hub_console_sessions
47
+ bro_hub_audit_events].freeze
48
+
49
+ # Always rebuilds the tables, so a stale one from an older version can't linger.
33
50
  def load_schema
34
51
  verbose = ActiveRecord::Migration.verbose
35
- load MIGRATION unless defined?(::CreateBroHubAuditEvents)
52
+ load MIGRATION unless defined?(::CreateBroHubTables)
36
53
  ActiveRecord::Migration.verbose = false
37
54
  connection = ActiveRecord::Base.connection
38
- connection.drop_table(:bro_hub_audit_events, if_exists: true)
39
- ::CreateBroHubAuditEvents.new.migrate(:up)
55
+ TABLES.each { |table| connection.drop_table(table, if_exists: true) }
56
+ ::CreateBroHubTables.new.migrate(:up)
40
57
  BroHub::AuditEvent.reset_column_information
41
58
  ensure
42
59
  ActiveRecord::Migration.verbose = verbose
@@ -1,3 +1,3 @@
1
1
  module BroHub
2
- VERSION = "0.2.0"
2
+ VERSION = "0.3.0"
3
3
  end
data/lib/bro_hub.rb CHANGED
@@ -1,20 +1,27 @@
1
1
  require "bro_hub/version"
2
+ require "bro_hub/features"
2
3
  require "bro_hub/configuration"
3
4
  require "bro_hub/section"
4
5
  require "bro_hub/registry"
5
6
  require "bro_hub/layout"
6
7
  require "bro_hub/controller_base"
7
- require "bro_hub/root_middleware"
8
8
  require "bro_hub/audit"
9
+ require "bro_hub/schema"
10
+ require "bro_hub/safe"
11
+ require "bro_hub/env"
12
+ require "bro_hub/apm"
13
+ require "bro_hub/cache"
9
14
  require "bro_hub/engine"
10
15
 
11
- # The shared admin shell for the Bro gems.
16
+ # One admin dashboard with opt-in features (see BroHub::FEATURES):
12
17
  #
13
- # BroHub.register :safe_bro, name: "SafeBro", label: "SafeBro · audit", accent: :red,
14
- # engine: "SafeBro::Engine",
15
- # items: [ { label: "Sessions", path: "/", badge: -> { SafeBro::Session.pending.count } } ],
16
- # visible_to: ->(user) { SafeBro.config.can_audit.call(user) }
18
+ # BroHub.configure { |config| config.features = %i[safe env] }
19
+ #
20
+ # Each enabled feature lives under <mount>/<key> and gets a sidebar section.
17
21
  module BroHub
22
+ # Raised by a feature's controller when this person may not use the feature. Answered with a 403.
23
+ class Forbidden < StandardError; end
24
+
18
25
  SKULL_PATH = File.expand_path("bro_hub/skull.png", __dir__)
19
26
  STYLES_PATH = File.expand_path("bro_hub/styles.css", __dir__)
20
27
 
@@ -27,6 +34,10 @@ module BroHub
27
34
  yield config
28
35
  end
29
36
 
37
+ def feature?(key)
38
+ config.features.include?(key.to_s.to_sym)
39
+ end
40
+
30
41
  def registry
31
42
  @registry ||= Registry.new
32
43
  end
@@ -36,6 +47,20 @@ module BroHub
36
47
  registry.register(Section.new(key, **options))
37
48
  end
38
49
 
50
+ # The sidebar: one section per enabled feature, rebuilt from scratch. Run at boot and by Testing.with_features.
51
+ def register_feature_sections!
52
+ registry.clear
53
+ FEATURES.each do |key, feature|
54
+ next unless feature?(key)
55
+
56
+ register key, label: feature[:label], accent: feature[:accent], order: feature[:order],
57
+ items: feature[:namespace].constantize::SIDEBAR_ITEMS,
58
+ visible_to: ->(user) { config.public_send(key).allows_any?(user) },
59
+ audit_visible_to: ->(user) { config.public_send(key).audit_visible?(user) }
60
+ end
61
+ registry
62
+ end
63
+
39
64
  def skull_data_uri
40
65
  @skull_data_uri ||= "data:image/png;base64,#{[ File.binread(SKULL_PATH) ].pack("m0")}"
41
66
  end
@@ -4,43 +4,40 @@ module BroHub
4
4
  module Generators
5
5
  # bin/rails generate bro_hub:install
6
6
  #
7
- # Mounts the dashboard and installs every Bro gem in the bundle (the ones that registered a section).
7
+ # Adds the initializer, copies the migration and mounts the dashboard.
8
8
  class InstallGenerator < Rails::Generators::Base
9
9
  source_root File.expand_path("templates", __dir__)
10
10
 
11
- desc "Mounts the BroHub dashboard and runs the installer of each Bro gem in your bundle."
11
+ desc "Mounts the BroHub dashboard, adds its initializer and copies its migration."
12
12
 
13
13
  DEFAULT_MOUNT_PATH = "/bro_hub"
14
14
 
15
15
  class_option :mount_path, type: :string,
16
16
  desc: "Where to mount the dashboard (asked interactively when omitted, default #{DEFAULT_MOUNT_PATH})"
17
- class_option :install_gems, type: :boolean, default: true, hide: true,
18
- desc: "Also run the installers of the Bro gems in the bundle"
19
- class_option :remove_direct_mounts, type: :boolean, default: nil,
20
- desc: "Comment out old `mount SafeBro::Engine`-style lines (asked interactively when omitted)"
21
17
 
22
- # Bro gems that only work with BroHub from these versions on.
23
- MINIMUM_VERSIONS = { "env_bro" => "0.2.0", "safe_bro" => "0.1.0" }.freeze
18
+ class_option :features, type: :string,
19
+ desc: "Comma separated features to turn on: #{BroHub::FEATURES.keys.join(", ")} " \
20
+ "(asked one by one when omitted in a terminal; otherwise env, safe, cache, plus apm when the dead_bro gem is installed)"
24
21
 
25
- def check_gem_versions
26
- MINIMUM_VERSIONS.each do |name, minimum|
27
- installed = Gem.loaded_specs[name]&.version
28
- next if installed.nil? || installed >= Gem::Version.new(minimum)
29
-
30
- say_status :warning, "#{name} #{installed} is too old for BroHub (needs #{minimum}+), so it is not installed " \
31
- "and its old mount is left alone. Run `bundle update #{name}` and install again.", :red
32
- end
33
- end
22
+ class_option :migrate, type: :boolean,
23
+ desc: "Run bin/rails db:migrate after copying the migration (asked in a terminal when omitted)"
34
24
 
35
25
  def copy_initializer
36
- if File.exist?(File.join(destination_root, "config/initializers/bro_hub.rb"))
26
+ path = File.join(destination_root, "config/initializers/bro_hub.rb")
27
+ if File.exist?(path)
37
28
  say_status :skip, "config/initializers/bro_hub.rb already exists, leaving it alone", :yellow
29
+ # An existing initializer without a features line turns every feature off until it gets one.
30
+ unless File.read(path).match?(/^\s*config\.features\s*=/)
31
+ @features_line_missing = true
32
+ say_status :warning, "config/initializers/bro_hub.rb has no config.features line, so no feature is on. " \
33
+ "Add it inside BroHub.configure: #{features_line}", :red
34
+ end
38
35
  else
39
- copy_file "bro_hub.rb", "config/initializers/bro_hub.rb"
36
+ template "bro_hub.rb.tt", "config/initializers/bro_hub.rb"
40
37
  end
41
38
  end
42
39
 
43
- # The one audit table every Bro gem writes to. Copied once: running the installer again skips it.
40
+ # BroHub's tables, all in one migration. Copied once: running the installer again skips it.
44
41
  def copy_migrations
45
42
  rails_command "bro_hub:install:migrations", inline: true
46
43
  end
@@ -53,42 +50,85 @@ module BroHub
53
50
  end
54
51
  end
55
52
 
56
- # A gem mounted directly *and* under the hub would be served twice.
57
- def retire_direct_mounts
58
- direct_mounts.each do |line|
59
- if remove_direct_mount?(line)
60
- indent = line[/\A\s*/]
61
- gsub_file "config/routes.rb", line, "#{indent}# BroHub mounts this now: #{line.strip}"
62
- else
63
- say_status :warning, "#{line.strip} is still mounted directly; BroHub also serves it under #{mount_path}. " \
64
- "Re-run with --remove-direct-mounts or delete the line.", :yellow
65
- end
53
+ def migrate
54
+ rails_command "db:migrate", inline: true if migrate?
55
+ end
56
+
57
+ def next_steps
58
+ steps = []
59
+ steps << "bin/rails db:migrate (creates BroHub's tables)" unless migrate?
60
+ if @features_line_missing
61
+ steps << "Add #{features_line} to config/initializers/bro_hub.rb: until then no feature is on and their pages don't exist"
62
+ else
63
+ steps << "Check config/initializers/bro_hub.rb (which features are on, who may use each)"
64
+ end
65
+ if features.any? && !@features_line_missing
66
+ urls = features.map { |key| "#{mount_path}/#{key}" } + [ "#{mount_path}/audit (every feature's audit log)" ]
67
+ steps << "Visit #{urls.join(", ")}"
66
68
  end
69
+ lines = steps.each_with_index.map { |step, index| " #{index + 1}. #{step}" }
70
+ lines.insert(0, " (db:migrate was not run: no --migrate, and nothing to answer the question.)") if !migrate? && options[:migrate].nil? && !interactive?
71
+ if features.empty?
72
+ lines << " Note: no feature is enabled (config.features is empty). Add any of #{BroHub::FEATURES.keys.join(", ")} to turn one on."
73
+ end
74
+ say "\nBroHub is installed. Next:\n#{lines.join("\n")}\n"
67
75
  end
68
76
 
69
- def install_bro_gems
70
- return unless options[:install_gems]
77
+ private
78
+ def interactive?
79
+ $stdin.tty?
80
+ end
71
81
 
72
- bro_gem_installers.each do |section, namespace|
73
- say_status :install, "#{section.name} (#{namespace})", :green
74
- invoke namespace, [], { skip_bro_hub: true, mount_path: mount_path }.merge(conflict_options)
82
+ def features
83
+ @features ||= begin
84
+ raw = options[:features]
85
+ chosen = if raw.nil?
86
+ interactive? ? ask_features : default_features
87
+ else
88
+ raise Thor::Error, "--features needs at least one of: #{BroHub::FEATURES.keys.join(", ")}." if raw.strip.empty?
89
+ raw.split(",").map { |key| key.strip.to_sym }
90
+ end
91
+ unknown = chosen - BroHub::FEATURES.keys
92
+ raise Thor::Error, "Unknown feature #{unknown.first}. Choose from #{BroHub::FEATURES.keys.join(", ")}." if unknown.any?
93
+ chosen.uniq
94
+ end
75
95
  end
76
- end
77
96
 
78
- def next_steps
79
- say <<~TEXT
97
+ def features_line
98
+ "config.features = %i[ #{features.join(" ")} ]"
99
+ end
80
100
 
81
- BroHub is installed. Next:
82
- 1. bin/rails db:migrate (creates the audit table all the Bro gems share)
83
- 2. Check config/initializers/bro_hub.rb (how to find the signed-in user)
84
- 3. Visit #{mount_path}. Each Bro gem lives under #{mount_path}/<gem>, the combined audit log under #{mount_path}/audit
85
- TEXT
86
- end
101
+ def default_features
102
+ %i[ env safe cache ] + (Gem.loaded_specs["dead_bro"] ? %i[ apm ] : [])
103
+ end
87
104
 
88
- private
89
- # Pass --skip/--force/--pretend/--quiet on to the installers of the other gems.
90
- def conflict_options
91
- options.slice(:force, :skip, :pretend, :quiet).to_h.symbolize_keys.select { |_, value| value }
105
+ def ask_features
106
+ BroHub::FEATURES.keys.select do |key|
107
+ confirm "Turn on #{key}?", default: default_features.include?(key)
108
+ end
109
+ end
110
+
111
+ def migrate?
112
+ return @migrate if defined?(@migrate)
113
+ @migrate = options[:migrate]
114
+ @migrate = ask_migrate if @migrate.nil? && interactive?
115
+ @migrate = false if @migrate.nil?
116
+ @migrate
117
+ end
118
+
119
+ def ask_migrate
120
+ confirm "Run bin/rails db:migrate now?", default: true
121
+ end
122
+
123
+ # A yes/no question; an empty answer takes the default.
124
+ def confirm(question, default:)
125
+ answer = ask("#{question} (#{default ? "Y/n" : "y/N"})").to_s.strip.downcase
126
+ answer.empty? ? default : answer.start_with?("y")
127
+ end
128
+
129
+ # A line of the initializer: live when the feature is on, commented out when it is off.
130
+ def feature_line(key, line)
131
+ features.include?(key) ? " #{line}" : " # #{line}"
92
132
  end
93
133
 
94
134
  def routes_source
@@ -100,7 +140,7 @@ module BroHub
100
140
  @mount_path ||= begin
101
141
  path = options[:mount_path].presence
102
142
  path ||= existing_mount_path
103
- path ||= ask("Where should the dashboard be mounted?", default: DEFAULT_MOUNT_PATH) if $stdin.tty?
143
+ path ||= ask("Where should the dashboard be mounted?", default: DEFAULT_MOUNT_PATH) if interactive?
104
144
  path = path.to_s.strip.presence || DEFAULT_MOUNT_PATH
105
145
  "/" + path.delete_prefix("/").delete_suffix("/")
106
146
  end
@@ -109,28 +149,6 @@ module BroHub
109
149
  def existing_mount_path
110
150
  routes_source[/mount BroHub::Engine => "([^"]+)"/, 1]
111
151
  end
112
-
113
- # Routes that mount an engine BroHub now mounts itself.
114
- def direct_mounts
115
- engines = BroHub.registry.filter_map { |section| section.engine&.name }
116
- routes_source.lines.map(&:chomp).select do |line|
117
- !line.strip.start_with?("#") && engines.any? { |name| line.match?(/\A\s*mount\s+#{Regexp.escape(name)}\b/) }
118
- end
119
- end
120
-
121
- def remove_direct_mount?(line)
122
- return options[:remove_direct_mounts] unless options[:remove_direct_mounts].nil?
123
-
124
- $stdin.tty? && yes?("#{line.strip} is now mounted by BroHub. Comment it out? (y/N)")
125
- end
126
-
127
- # [ [ section, "safe_bro:install" ], ... ] for the registered gems that ship an installer.
128
- def bro_gem_installers
129
- BroHub.registry.filter_map do |section|
130
- namespace = "#{section.key}:install"
131
- [ section, namespace ] if section.engine && Rails::Generators.find_by_namespace(namespace)
132
- end
133
- end
134
152
  end
135
153
  end
136
154
  end