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,104 @@
1
+ module BroHub::Apm
2
+ module ApplicationHelper
3
+ # The apm feature's additions to BroHub's styles, once per page (and nonce-friendly).
4
+ def apm_styles
5
+ content_for(:head, render("bro_hub/apm/shared/page_styles")) unless content_for?(:head)
6
+ nil
7
+ end
8
+
9
+ def apm_int(value)
10
+ value.nil? ? "-" : number_with_delimiter(value)
11
+ end
12
+
13
+ def apm_ms(value)
14
+ return "-" if value.nil?
15
+
16
+ value = value.to_f
17
+ value >= 1000 ? "#{(value / 1000).round(2)} s" : "#{value.round(value < 10 ? 2 : 1)} ms"
18
+ end
19
+
20
+ def apm_pct(value)
21
+ value.nil? ? "-" : "#{value}%"
22
+ end
23
+
24
+ # ISO8601 string from the API, or a Time/epoch from the gem's own state -> "5 minutes ago", exact time on hover.
25
+ def apm_time(value)
26
+ time = case value
27
+ when nil, "" then nil
28
+ when Time, ActiveSupport::TimeWithZone then value
29
+ when Numeric then Time.at(value)
30
+ else parse_api_time(value)
31
+ end
32
+ return content_tag(:span, "-", class: "bh-cell-muted") unless time
33
+
34
+ content_tag(:span, "#{time_ago_in_words(time)} ago", title: time.utc.iso8601)
35
+ end
36
+
37
+ # A malformed value from the API shows as "-" instead of taking the page down.
38
+ def parse_api_time(value)
39
+ Time.zone.parse(value.to_s)
40
+ rescue ArgumentError, RangeError
41
+ nil
42
+ end
43
+
44
+ def apm_error_rate_tone(rate)
45
+ rate = rate.to_f
46
+ rate >= 5 ? :red : (rate >= 1 ? :amber : :green)
47
+ end
48
+
49
+ def apm_tag(text, style = nil)
50
+ content_tag(:span, text, class: [ "bh-tag", style ].compact_blank)
51
+ end
52
+
53
+ # What went wrong reaching DeadBro, in words that say what to do about it.
54
+ def apm_error_notice(error)
55
+ advice = case error.kind
56
+ when :not_configured then "Configure the dead_bro gem with this app's API key."
57
+ when :unauthorized then "Check the API key in the dead_bro configuration: DeadBro does not recognise it."
58
+ when :unavailable then "DeadBro could not read its data just now. Try again in a minute."
59
+ when :network then "This server could not reach DeadBro. Check the network and the apm base_url."
60
+ else "Try again in a minute."
61
+ end
62
+ content_tag(:div, class: "bh-alert bh-alert-error") { safe_join([ content_tag(:strong, error.message), " ", advice ]) }
63
+ end
64
+
65
+ # Tiny bar chart: values -> inline SVG, one bar per value, scaled to the largest.
66
+ def apm_bars(values, tone: "var(--bh-violet)", width: 420, height: 56)
67
+ values = Array(values).map(&:to_f)
68
+ return content_tag(:div, "No data in this window", class: "bh-cell-muted") if values.empty? || values.max <= 0
69
+
70
+ gap = 2
71
+ bar = [ (width - gap * (values.size - 1)).fdiv(values.size), 1 ].max
72
+ rects = values.each_with_index.map do |value, i|
73
+ h = [ value / values.max * height, 1 ].max
74
+ tag.rect(x: (i * (bar + gap)).round(2), y: (height - h).round(2), width: bar.round(2), height: h.round(2), fill: tone)
75
+ end
76
+ tag.svg(safe_join(rects), viewBox: "0 0 #{width} #{height}", width: "100%", height: height, preserveAspectRatio: "none",
77
+ role: "img", class: "dbh-bars")
78
+ end
79
+
80
+ # A row of chips linking to the same page with one param changed.
81
+ def apm_chips(param, options, current, label_for: nil)
82
+ links = options.map do |option|
83
+ link_to((label_for ? label_for.call(option) : option), url_for(request.query_parameters.symbolize_keys.merge(param => option, offset: nil)),
84
+ class: [ "bh-chip", ("is-on" if option.to_s == current.to_s) ])
85
+ end
86
+ safe_join(links, " ")
87
+ end
88
+
89
+ def apm_pager(rows_shown, per_page, offset)
90
+ links = []
91
+ links << link_to("← Newer", url_for(request.query_parameters.symbolize_keys.merge(offset: [ offset - per_page, 0 ].max)), class: "bh-link-quiet") if offset.positive?
92
+ links << link_to("Older →", url_for(request.query_parameters.symbolize_keys.merge(offset: offset + per_page)), class: "bh-link-quiet") if rows_shown >= per_page
93
+ return if links.empty?
94
+
95
+ content_tag(:div, class: "bh-pager") { safe_join([ content_tag(:span, "#{offset + 1}-#{offset + rows_shown}", class: "bh-meta"), *links ]) }
96
+ end
97
+
98
+ def apm_yes_no(value, yes: "on", no: "off")
99
+ return apm_tag("unknown") if value.nil?
100
+
101
+ value ? apm_tag(yes, "is-green") : apm_tag(no, "is-amber")
102
+ end
103
+ end
104
+ end
@@ -1,30 +1,16 @@
1
1
  module BroHub
2
2
  module ApplicationHelper
3
- # The mount point of the hub, without a trailing slash ("" when mounted at "/"), or nil when this page is
4
- # not served through the hub (a Bro gem the host mounted on its own). The hub records its mount point in the
5
- # request as it hands over to an engine, so a gem mounted at a path that merely looks like "<hub>/<key>"
6
- # is not mistaken for one.
3
+ # The mount point of the hub, without a trailing slash ("" when mounted at "/").
7
4
  def bro_hub_root
8
- return @bro_hub_root if defined?(@bro_hub_root)
9
-
10
- @bro_hub_root =
11
- if request.env["bro_hub.root"] then request.env["bro_hub.root"]
12
- elsif controller.try(:bro_hub_section_key).nil? then request.script_name.to_s.delete_suffix("/")
13
- end
5
+ @bro_hub_root ||= request.script_name.to_s.delete_suffix("/")
14
6
  end
15
7
 
16
8
  # The sidebar: [ [section, base_path, current?], ... ] for what this person may see.
17
9
  def bro_hub_sections
18
10
  @bro_hub_sections ||= begin
19
- user = bro_hub_user
20
11
  current_key = controller.try(:bro_hub_section_key)
21
- sections = BroHub.registry.visible_to(user)
22
- # We can only link to what lives under the hub (it mounts the engines) or to the page we are on.
23
- # A section whose engine the host mounted elsewhere shows up inside its own pages only.
24
- sections = sections.select { |section| section.key == current_key || (bro_hub_root && section.engine) }
25
- sections.map do |section|
26
- base = bro_hub_root ? "#{bro_hub_root}/#{section.key}" : request.script_name.to_s.delete_suffix("/")
27
- [ section, base, section.key == current_key ]
12
+ BroHub.registry.visible_to(bro_hub_user).map do |section|
13
+ [ section, "#{bro_hub_root}/#{section.key}", section.key == current_key ]
28
14
  end
29
15
  end
30
16
  end
@@ -83,7 +69,7 @@ module BroHub
83
69
 
84
70
  # What the sidebar's own "Bro Hub" group links to: [ label, path, active? ] for this person, or none.
85
71
  def bro_hub_own_items
86
- return [] unless bro_hub_root && bro_hub_user && BroHub.registry.audited_by(bro_hub_user).any?
72
+ return [] unless bro_hub_user && BroHub.registry.audited_by(bro_hub_user).any?
87
73
 
88
74
  [ [ "Audit log", "#{bro_hub_root}/audit", request.path.start_with?("#{bro_hub_root}/audit") && controller.try(:bro_hub_section_key).nil? ] ]
89
75
  end
@@ -0,0 +1,63 @@
1
+ module BroHub::Cache
2
+ module ApplicationHelper
3
+ PER_PAGE = 50
4
+
5
+ EVENT_LABELS = {
6
+ "value_viewed" => "Revealed", "key_deleted" => "Deleted", "keys_purged" => "Purged", "store_flushed" => "Flushed"
7
+ }.freeze
8
+ EVENT_TONES = { "value_viewed" => "amber", "key_deleted" => "red", "keys_purged" => "red", "store_flushed" => "red" }.freeze
9
+
10
+ def cache_time(time)
11
+ return "-" unless time
12
+
13
+ content_tag(:time, time.utc.strftime("%Y-%m-%d %H:%M"), datetime: time.iso8601, title: time.utc.to_s)
14
+ end
15
+
16
+ def cache_ttl(seconds)
17
+ seconds ? "in #{distance_of_time_in_words(0, seconds.round, include_seconds: true)}" : "no expiry"
18
+ end
19
+
20
+ def cache_size(bytes)
21
+ bytes ? number_to_human_size(bytes) : "-"
22
+ end
23
+
24
+ def cache_count(count, singular, plural = singular.pluralize)
25
+ "#{number_with_delimiter(count)} #{count == 1 ? singular : plural}"
26
+ end
27
+
28
+ def cache_event_label(event)
29
+ EVENT_LABELS.fetch(event.to_s, event.to_s.humanize)
30
+ end
31
+
32
+ def cache_event_tag(event)
33
+ content_tag(:span, cache_event_label(event), class: "bh-tag is-#{EVENT_TONES.fetch(event.to_s, "muted")}")
34
+ end
35
+
36
+ # A reason box. Required when the config says so for that action.
37
+ def cache_reason_field(action, placeholder: "Why? (ticket, incident, ...)")
38
+ required = BroHub.config.cache.reason_required?(action)
39
+ label_tag(:reason, class: "bh-field") do
40
+ safe_join([ (required ? "Reason (required)" : "Reason (optional)"),
41
+ text_field_tag(:reason, nil, class: "bh-input", placeholder: placeholder, required: required, autocomplete: "off") ])
42
+ end
43
+ end
44
+
45
+ # "Next →" for SCAN cursors. There is no "back": a cursor only goes forward.
46
+ def cache_pager(listing, query:)
47
+ return unless listing.more?
48
+
49
+ content_tag(:div, class: "bh-meta", style: "margin-top:14px") do
50
+ link_to("Keep looking →", cache_root_path(store: cache_current_store.name, q: query, cursor: listing.cursor))
51
+ end
52
+ end
53
+
54
+ # "← Newer / Older →" for audit pages. `page` counts from 0.
55
+ def cache_audit_pager(total:, page:)
56
+ newer = link_to("← Newer", url_for(request.query_parameters.merge(page: page - 1))) if page > 0
57
+ older = link_to("Older →", url_for(request.query_parameters.merge(page: page + 1))) if (page + 1) * PER_PAGE < total
58
+ content_tag(:div, class: "bh-meta", style: "display:flex;justify-content:space-between;gap:16px;margin-top:14px") do
59
+ safe_join([ content_tag(:span, cache_count(total, "event")), content_tag(:span, safe_join([ newer, older ].compact, " ")) ])
60
+ end
61
+ end
62
+ end
63
+ end
@@ -0,0 +1,67 @@
1
+ module BroHub::Env
2
+ module ApplicationHelper
3
+ # EnvBro's additions to BroHub's styles, once per page (and nonce-friendly).
4
+ def env_styles
5
+ content_for(:head, render("bro_hub/env/shared/page_styles")) unless content_for?(:head)
6
+ nil
7
+ end
8
+
9
+ def env_masked(value)
10
+ return content_tag(:span, "(none)", class: "bh-cell-muted") if value.nil?
11
+ length = env_format_value(value).length
12
+ content_tag(:span, "•" * [ length, 12 ].min, class: "mask", title: "#{length} characters") +
13
+ content_tag(:span, " #{length} chars", class: "bh-cell-muted")
14
+ end
15
+
16
+ def env_value(value)
17
+ return content_tag(:span, "(none)", class: "bh-cell-muted") if value.nil?
18
+ content_tag(:code, env_format_value(value), class: "value")
19
+ end
20
+
21
+ def env_format_value(value)
22
+ value.is_a?(String) ? value : value.to_json
23
+ end
24
+
25
+ STATUS_TAGS = { "added" => "is-green", "changed" => "is-amber", "removed" => "is-red", "unchanged" => "" }.freeze
26
+
27
+ def env_status_badge(status)
28
+ content_tag(:span, status.to_s, class: [ "bh-tag", STATUS_TAGS[status.to_s], "tag-#{status}" ].compact_blank)
29
+ end
30
+
31
+ ENVIRONMENT_BADGES = {
32
+ ready: [ "ready", "is-green" ],
33
+ missing_file: [ "file missing", "is-red" ],
34
+ missing_key: [ "no key on server", "is-red" ],
35
+ wrong_key: [ "key doesn't match", "is-red" ]
36
+ }.freeze
37
+
38
+ def env_environment_badge(status)
39
+ label, style = ENVIRONMENT_BADGES.fetch(status)
40
+ content_tag(:span, label, class: "bh-tag #{style}")
41
+ end
42
+
43
+ def env_time(time)
44
+ time.utc.strftime("%Y-%m-%d %H:%M UTC")
45
+ end
46
+
47
+ # Status of a proposal_created event: live / deployed / superseded / pending.
48
+ def env_deployment_badge(proposal, live)
49
+ case proposal.deployment_status(live)
50
+ when :live then content_tag(:span, "live since #{env_time(proposal.deployment.created_at)}", class: "bh-tag is-green")
51
+ when :deployed then content_tag(:span, "deployed #{env_time(proposal.deployment.created_at)}, replaced since", class: "bh-tag")
52
+ when :superseded then content_tag(:span, "superseded", class: "bh-tag", title: "Never deployed. A newer proposal is live.")
53
+ else content_tag(:span, "not deployed yet", class: "bh-tag is-amber")
54
+ end
55
+ end
56
+
57
+ def env_display_path(path)
58
+ path.relative_path_from(Rails.root).to_s
59
+ rescue ArgumentError
60
+ path.to_s
61
+ end
62
+
63
+ def env_short_digest(digest)
64
+ digest.to_s.first(12)
65
+ end
66
+ end
67
+ end
@@ -0,0 +1,59 @@
1
+ module BroHub::Safe
2
+ module ApplicationHelper
3
+ PER_PAGE = 50
4
+
5
+ REVIEW_LABELS = { "pending" => "Pending", "approved" => "Appropriate", "flagged" => "Flagged" }.freeze
6
+ REVIEW_TONES = { "pending" => "muted", "approved" => "green", "flagged" => "red" }.freeze
7
+
8
+ def safe_time(time)
9
+ return "-" unless time
10
+
11
+ content_tag(:time, time.utc.strftime("%Y-%m-%d %H:%M"), datetime: time.iso8601, title: time.utc.to_s)
12
+ end
13
+
14
+ def safe_duration(seconds)
15
+ return "#{seconds}s" if seconds < 60
16
+ return "#{seconds / 60}m" if seconds < 3600
17
+
18
+ "#{seconds / 3600}h #{seconds % 3600 / 60}m"
19
+ end
20
+
21
+ def safe_review_label(status)
22
+ REVIEW_LABELS.fetch(status.to_s, status.to_s.capitalize)
23
+ end
24
+
25
+ def safe_review_tone(status)
26
+ REVIEW_TONES.fetch(status.to_s, "muted")
27
+ end
28
+
29
+ # Coloured review status, as text.
30
+ def safe_review_status(status)
31
+ content_tag(:span, safe_review_label(status), class: "bh-status bh-tone-#{safe_review_tone(status)}")
32
+ end
33
+
34
+ def safe_command_flag(command)
35
+ case command.status
36
+ when "blocked" then content_tag(:span, "Blocked", class: "bh-flag")
37
+ when "suspicious" then content_tag(:span, "Flagged", class: "bh-flag")
38
+ end
39
+ end
40
+
41
+ def safe_count(count, singular, plural = singular.pluralize)
42
+ "#{count} #{count == 1 ? singular : plural}"
43
+ end
44
+
45
+ # "← Newer / Older →" for pages of PER_PAGE rows. `page` counts from 0.
46
+ def safe_pager(total:, page:, noun:)
47
+ newer = link_to("← Newer", url_for(request.query_parameters.merge(page: page - 1))) if page > 0
48
+ older = link_to("Older →", url_for(request.query_parameters.merge(page: page + 1))) if (page + 1) * PER_PAGE < total
49
+ content_tag(:div, class: "bh-meta", style: "display:flex;justify-content:space-between;gap:16px;margin-top:14px") do
50
+ safe_join([ content_tag(:span, safe_count(total, noun)), content_tag(:span, safe_join([ newer, older ].compact, " ")) ])
51
+ end
52
+ end
53
+
54
+ # Short, readable text for a list of config values (never raw secrets: callers pass patterns and names).
55
+ def safe_rule(value)
56
+ value.respond_to?(:source) ? value.inspect : value.to_s
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,10 @@
1
+ module BroHub::Safe
2
+ # Schedule this (daily is plenty) to enforce BroHub.config.safe.retention.
3
+ class PurgeJob < ActiveJob::Base
4
+ queue_as :default
5
+
6
+ def perform
7
+ BroHub::Safe::Session.purge!
8
+ end
9
+ end
10
+ end
@@ -1,11 +1,7 @@
1
1
  module BroHub
2
2
  # Who did what, in any Bro gem. Append-only: a saved row can't be changed.
3
3
  #
4
- # Gems write rows with BroHub::Audit.record and read their own through a small subclass that sets `source`:
5
- #
6
- # class CacheBro::AuditEvent < BroHub::AuditEvent
7
- # default_scope { where(source: "cache_bro") }
8
- # end
4
+ # Features write rows with BroHub::Audit.record and read their own with AuditEvent.for_feature(:cache).
9
5
  class AuditEvent < ApplicationRecord
10
6
  # The subclasses share this table and are told apart by `source`, not by a type column.
11
7
  self.inheritance_column = nil
@@ -18,7 +14,7 @@ module BroHub
18
14
  validates :source, :event, :environment, presence: true
19
15
 
20
16
  scope :recent, -> { order(created_at: :desc, id: :desc) }
21
- scope :from_source, ->(source) { where(source: source.to_s) }
17
+ scope :for_feature, ->(key) { where(source: key.to_s) }
22
18
 
23
19
  def readonly?
24
20
  persisted? || super
@@ -0,0 +1,15 @@
1
+ module BroHub::Cache
2
+ # Who revealed, deleted or purged what, and when. Holds keys and patterns, never values.
3
+ # The rows live in BroHub's one audit table; this is CacheBro's slice of it.
4
+ class AuditEvent < BroHub::AuditEvent
5
+ SOURCE = "cache".freeze
6
+ EVENTS = %w[ value_viewed key_deleted keys_purged store_flushed ].freeze
7
+
8
+ default_scope { for_feature(SOURCE) }
9
+
10
+ validates :event, inclusion: { in: EVENTS }
11
+
12
+ # The cache store the action was on ("Rails.cache").
13
+ alias_attribute :store, :context
14
+ end
15
+ end
@@ -0,0 +1,72 @@
1
+ module BroHub::Env
2
+ # Who proposed, reviewed or revealed what, and when proposals went live.
3
+ # Holds key names only, never values.
4
+ # The rows live in BroHub's one audit table; this is EnvBro's slice of it.
5
+ class AuditEvent < BroHub::AuditEvent
6
+ SOURCE = "env".freeze
7
+ EVENTS = %w[proposal_created proposal_deployed credentials_deployed review_viewed values_revealed].freeze
8
+
9
+ default_scope { for_feature(SOURCE) }
10
+
11
+ # A proposal's row keeps the id embedded in its file's metadata and the SHA-256 of the file handed out.
12
+ alias_attribute :proposal_token, :reference
13
+ alias_attribute :file_digest, :digest
14
+
15
+ # A deployment row points back at the proposal it put live (BroHub's `parent`). Booting with a file nobody
16
+ # proposed (edited by hand, say) is a credentials_deployed row with no proposal.
17
+ belongs_to :proposal, class_name: "BroHub::Env::AuditEvent", foreign_key: :parent_id, optional: true
18
+ # A proposal can go live more than once (a rollback puts it back), so `deployment` is the latest.
19
+ has_one :deployment, -> { where(event: "proposal_deployed").order(created_at: :desc, id: :desc) }, class_name: "BroHub::Env::AuditEvent", foreign_key: :parent_id
20
+
21
+ DEPLOYMENT_EVENTS = %w[proposal_deployed credentials_deployed].freeze
22
+
23
+ validates :event, inclusion: { in: EVENTS }
24
+ scope :proposals, -> { where(event: "proposal_created") }
25
+ scope :deployments, -> { where(event: DEPLOYMENT_EVENTS) }
26
+
27
+ # Audit entries are append-only.
28
+ def readonly?
29
+ persisted? || super
30
+ end
31
+
32
+ # Key names touched by the event, for display.
33
+ def keys
34
+ if event == "proposal_deployed"
35
+ proposal&.keys || []
36
+ elsif details["changes"]
37
+ details["changes"].map { |c| "#{c['action']} #{c['key']}" }
38
+ else
39
+ Array(details["changed_keys"] || details["keys"])
40
+ end
41
+ end
42
+
43
+ # The proposal whose file is running right now, if it came from EnvBro: the one the latest deployment points
44
+ # at, which is none when the latest deployment was a file nobody proposed.
45
+ def self.live_proposal
46
+ deployments.recent.first&.proposal
47
+ end
48
+
49
+ # For a proposal_created event:
50
+ # :live - its file is what's deployed now
51
+ # :deployed - it was deployed, a later deployment (another proposal, or a file nobody proposed) replaced it
52
+ # :superseded - never deployed, and a newer proposal is live
53
+ # :pending - not deployed (yet)
54
+ def deployment_status(live = self.class.live_proposal)
55
+ if live&.id == id
56
+ :live
57
+ elsif deployment
58
+ :deployed
59
+ elsif live && live.created_at > created_at
60
+ :superseded
61
+ else
62
+ :pending
63
+ end
64
+ end
65
+
66
+ # The deployed file differs from the one EnvBro handed out (re-saved with
67
+ # `rails credentials:edit` after review, for instance).
68
+ def modified_after_review?
69
+ event == "proposal_deployed" && details["modified_after_review"] == true
70
+ end
71
+ end
72
+ end
@@ -0,0 +1,22 @@
1
+ require "bro_hub/safe/encrypted_type"
2
+
3
+ module BroHub::Safe
4
+ class Command < BroHub::ApplicationRecord
5
+ self.table_name = "bro_hub_console_commands"
6
+
7
+ belongs_to :session
8
+ belongs_to :unlock, optional: true
9
+
10
+ attribute :statements, BroHub::Safe::EncryptedType.new
11
+
12
+ # executed: ran normally. suspicious: ran, but flagged. blocked: never ran.
13
+ enum :status, { executed: 0, suspicious: 1, blocked: 2 }
14
+
15
+ scope :flagged, -> { where(status: [ statuses[:suspicious], statuses[:blocked] ]) }
16
+ scope :chronological, -> { order(:created_at, :id) }
17
+
18
+ def flagged?
19
+ suspicious? || blocked?
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,22 @@
1
+ require "bro_hub/safe/encrypted_type"
2
+
3
+ module BroHub::Safe
4
+ # A reviewer's verdict on a session. Reviews are append-only: reviewing again adds a new row,
5
+ # so the history of who decided what is kept.
6
+ class Review < BroHub::ApplicationRecord
7
+ self.table_name = "bro_hub_console_reviews"
8
+
9
+ belongs_to :session
10
+
11
+ enum :status, { approved: 1, flagged: 2 }
12
+
13
+ attribute :notes, BroHub::Safe::EncryptedType.new
14
+
15
+ validates :reviewer, presence: true
16
+ validates :notes, presence: true, if: :flagged?
17
+
18
+ after_create { session.update!(review_status: status) }
19
+ after_create { Trail.record(:session_reviewed, session: session, user: reviewer, status: status, session_user: session.username) }
20
+ after_create { BroHub::Safe.notify(:session_flagged, session: session, reviewer: reviewer, notes: notes) if flagged? }
21
+ end
22
+ end
@@ -0,0 +1,57 @@
1
+ module BroHub::Safe
2
+ # One console session: who, why, from where, and everything they did.
3
+ class Session < BroHub::ApplicationRecord
4
+ self.table_name = "bro_hub_console_sessions"
5
+
6
+ has_many :commands, dependent: :delete_all
7
+ has_many :unlocks, dependent: :delete_all
8
+ has_many :reviews, dependent: :delete_all
9
+
10
+ # The latest review decides the status.
11
+ enum :review_status, { pending: 0, approved: 1, flagged: 2 }, prefix: :review
12
+
13
+ validates :username, :reason, :started_at, presence: true
14
+
15
+ scope :chronological, -> { order(started_at: :desc, id: :desc) }
16
+ scope :on_or_after, ->(time) { where(started_at: time..) }
17
+ scope :before, ->(time) { where(started_at: ...time) }
18
+
19
+ # Sessions that deserve a look: someone unlocked sensitive data or a command was flagged.
20
+ scope :needing_attention, -> {
21
+ where(id: Unlock.select(:session_id)).or(where(id: Command.flagged.select(:session_id)))
22
+ }
23
+
24
+ # Sessions that nobody has reviewed yet.
25
+ scope :awaiting_review, -> { where(review_status: :pending) }
26
+
27
+ class << self
28
+ # Deletes old sessions and everything under them, including their rows in BroHub's audit log. Flagged ones stay
29
+ # unless told otherwise.
30
+ def purge!(older_than: BroHub.config.safe.retention, keep_flagged: BroHub.config.safe.keep_flagged)
31
+ return 0 if older_than.nil?
32
+
33
+ scope = where(started_at: ...older_than.ago)
34
+ scope = scope.where.not(review_status: :flagged) if keep_flagged
35
+ purged_ids = scope.find_each.select(&:destroy).map(&:id)
36
+ BroHub::AuditEvent.for_feature(:safe).where(reference: purged_ids.map(&:to_s)).delete_all if purged_ids.any?
37
+ purged_ids.size
38
+ end
39
+ end
40
+
41
+ def sensitive?
42
+ unlocks.exists? || commands.flagged.exists?
43
+ end
44
+
45
+ def open?
46
+ ended_at.nil?
47
+ end
48
+
49
+ def duration
50
+ ((ended_at || Time.current) - started_at).to_i
51
+ end
52
+
53
+ def last_review
54
+ reviews.order(:id).last
55
+ end
56
+ end
57
+ end
@@ -0,0 +1,15 @@
1
+ module BroHub::Safe
2
+ # A window during which the console was unlocked, with the justification given for it.
3
+ class Unlock < BroHub::ApplicationRecord
4
+ self.table_name = "bro_hub_console_unlocks"
5
+
6
+ belongs_to :session
7
+ has_many :commands, dependent: :nullify
8
+
9
+ validates :justification, :resources, :started_at, presence: true
10
+
11
+ def open?
12
+ ended_at.nil?
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,21 @@
1
+ <% apm_styles %>
2
+ <% bro_hub_crumb "Deploys" %>
3
+ <%= bro_hub_hero eyebrow: "Releases", title: "Deploys", tone: :violet, lead: "Detected from the revision your app reports. Errors are counted per deploy." %>
4
+ <% if @error %>
5
+ <%= apm_error_notice(@error) %>
6
+ <% elsif @data["deploys"].empty? %>
7
+ <div class="bh-table-wrap"><div class="bh-empty">No deploys recorded yet.</div></div>
8
+ <% else %>
9
+ <div class="bh-table-wrap"><div class="bh-table dbh-cols-deploys">
10
+ <div class="bh-row is-head"><span>Revision</span><span>Deployed</span><span>State</span><span>Errors</span><span>Per hour</span></div>
11
+ <% @data["deploys"].each do |d| %>
12
+ <div class="bh-row">
13
+ <span class="bh-cell-strong"><code><%= truncate(d["revision"].to_s, length: 24) %></code></span>
14
+ <span class="bh-cell-muted"><%= apm_time(d["deployed_at"]) %></span>
15
+ <span><%= d["finished"] ? apm_tag("replaced") : apm_tag("live", "is-green") %></span>
16
+ <span class="<%= "bh-tone-red" if d["error_count"].to_i.positive? %>"><%= apm_int(d["error_count"]) %></span>
17
+ <span class="bh-cell-muted"><%= d["errors_per_hour"] %></span>
18
+ </div>
19
+ <% end %>
20
+ </div></div>
21
+ <% end %>
@@ -0,0 +1,27 @@
1
+ <% apm_styles %>
2
+ <% bro_hub_crumb "Endpoints" %>
3
+ <%= bro_hub_hero eyebrow: "Performance", title: "Endpoints", tone: :violet,
4
+ lead: "Controller actions and jobs, ranked. Window and ranking are yours to change." %>
5
+ <div class="bh-filters">
6
+ <span><%= apm_chips(:window, %w[1h 24h 7d 30d], @data&.fetch("window", nil) || "24h") %></span>
7
+ <span><%= apm_chips(:sort, %w[mean_duration error_rate slow_count n_plus_one cpu_heavy], @data&.fetch("sort", nil) || "mean_duration", label_for: ->(s) { s.humanize.downcase }) %></span>
8
+ </div>
9
+ <% if @error %>
10
+ <%= apm_error_notice(@error) %>
11
+ <% elsif @data["endpoints"].empty? %>
12
+ <div class="bh-table-wrap"><div class="bh-empty">No requests in this window.</div></div>
13
+ <% else %>
14
+ <div class="bh-table-wrap"><div class="bh-table dbh-cols-endpoints">
15
+ <div class="bh-row is-head"><span>Endpoint</span><span>Requests</span><span>Mean</span><span>Errors</span><span>Slow</span><span>N+1</span></div>
16
+ <% @data["endpoints"].each do |e| %>
17
+ <div class="bh-row">
18
+ <span class="bh-cell-strong"><%= e["name"] %></span>
19
+ <span><%= apm_int(e["requests"]) %></span>
20
+ <span><%= apm_ms(e["mean_duration_ms"]) %></span>
21
+ <span class="<%= "bh-tone-#{apm_error_rate_tone(e["error_rate_pct"])}" %>"><%= apm_pct(e["error_rate_pct"]) %></span>
22
+ <span class="bh-cell-muted"><%= apm_int(e["slow_count"]) %></span>
23
+ <span class="bh-cell-muted"><%= apm_int(e["n_plus_one_count"]) %></span>
24
+ </div>
25
+ <% end %>
26
+ </div></div>
27
+ <% end %>
@@ -0,0 +1,22 @@
1
+ <% apm_styles %>
2
+ <% bro_hub_crumb "Errors" %>
3
+ <%= bro_hub_hero eyebrow: "Exceptions", title: (@data ? apm_int(@data["total"]) : "-"), subtitle: "distinct errors", tone: :red,
4
+ lead: "Grouped by fingerprint, most recently seen first." %>
5
+ <% if @error %>
6
+ <%= apm_error_notice(@error) %>
7
+ <% elsif @data["errors"].empty? %>
8
+ <div class="bh-table-wrap"><div class="bh-empty">No errors recorded. Nice.</div></div>
9
+ <% else %>
10
+ <div class="bh-table-wrap"><div class="bh-table dbh-cols-errors">
11
+ <div class="bh-row is-head"><span>Error</span><span>Count</span><span>First seen</span><span>Last seen</span></div>
12
+ <% @data["errors"].each do |e| %>
13
+ <%= link_to apm_error_path(e["id"]), class: "bh-row" do %>
14
+ <span><span class="bh-cell-strong"><%= e["exception_class"] || "Error" %></span><br><span class="bh-cell-muted"><%= truncate(e["message"].to_s, length: 140) %></span></span>
15
+ <span><%= apm_int(e["occurrences"]) %></span>
16
+ <span class="bh-cell-muted"><%= apm_time(e["first_seen_at"]) %></span>
17
+ <span class="bh-cell-muted"><%= apm_time(e["last_seen_at"]) %></span>
18
+ <% end %>
19
+ <% end %>
20
+ </div></div>
21
+ <%= apm_pager(@data["errors"].size, BroHub::Apm::ErrorsController::PER_PAGE, @offset) %>
22
+ <% end %>
@@ -0,0 +1,3 @@
1
+ <% bro_hub_crumb "Errors", "Not found" %>
2
+ <% content_for :bro_hub_crumb_actions do %><%= bro_hub_crumb_link "← All errors", apm_errors_path %><% end %>
3
+ <%= bro_hub_hero eyebrow: "Exceptions", title: "Not found", tone: :red, lead: "DeadBro has no such error for this app." %>