open-loam 0.2.0 → 0.4.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 (75) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +178 -0
  3. data/README.md +4 -2
  4. data/app/jobs/open_loam/event_log_prune_job.rb +15 -0
  5. data/app/jobs/open_loam/webhook_delivery_job.rb +22 -35
  6. data/app/jobs/open_loam/webhook_sweep_job.rb +22 -0
  7. data/app/models/open_loam/api_token.rb +27 -4
  8. data/app/models/open_loam/event_record.rb +42 -0
  9. data/app/models/open_loam/pending_action.rb +47 -3
  10. data/app/models/open_loam/sso_provider.rb +31 -0
  11. data/app/models/open_loam/webhook_delivery.rb +40 -0
  12. data/app/models/open_loam/webhook_endpoint.rb +130 -11
  13. data/app/views/open_loam/custom_fields/_fields.html.erb +4 -0
  14. data/lib/generators/open_loam/entity/templates/api_controller.rb +1 -0
  15. data/lib/generators/open_loam/entity/templates/controller.rb +11 -1
  16. data/lib/generators/open_loam/entity/templates/views/_form.html.erb +4 -1
  17. data/lib/generators/open_loam/entity/templates/views/index.html.erb +6 -2
  18. data/lib/generators/open_loam/entity/templates/views/show.html.erb +2 -0
  19. data/lib/generators/open_loam/install/install_generator.rb +13 -0
  20. data/lib/generators/open_loam/install/templates/AGENTS.md +6 -2
  21. data/lib/generators/open_loam/install/templates/admin/api_tokens_controller.rb +25 -7
  22. data/lib/generators/open_loam/install/templates/admin/api_tokens_index.html.erb +23 -0
  23. data/lib/generators/open_loam/install/templates/admin/base_controller.rb +63 -0
  24. data/lib/generators/open_loam/install/templates/admin/dashboard_controller.rb +2 -0
  25. data/lib/generators/open_loam/install/templates/admin/events_controller.rb +2 -0
  26. data/lib/generators/open_loam/install/templates/admin/history_controller.rb +26 -0
  27. data/lib/generators/open_loam/install/templates/admin/history_index.html.erb +1 -1
  28. data/lib/generators/open_loam/install/templates/admin/imports_controller.rb +13 -1
  29. data/lib/generators/open_loam/install/templates/admin/inbound_webhook_sources_controller.rb +1 -1
  30. data/lib/generators/open_loam/install/templates/admin/inbound_webhook_sources_new.html.erb +0 -2
  31. data/lib/generators/open_loam/install/templates/admin/mfa_controller.rb +5 -0
  32. data/lib/generators/open_loam/install/templates/admin/notifications_controller.rb +2 -0
  33. data/lib/generators/open_loam/install/templates/admin/perspectives_controller.rb +6 -0
  34. data/lib/generators/open_loam/install/templates/admin/progress_jobs_controller.rb +4 -0
  35. data/lib/generators/open_loam/install/templates/admin/search_controller.rb +2 -0
  36. data/lib/generators/open_loam/install/templates/admin/sessions_controller.rb +3 -4
  37. data/lib/generators/open_loam/install/templates/admin/sso_providers_index.html.erb +8 -1
  38. data/lib/generators/open_loam/install/templates/admin/sudo_controller.rb +3 -1
  39. data/lib/generators/open_loam/install/templates/admin/webhook_endpoints_controller.rb +4 -1
  40. data/lib/generators/open_loam/install/templates/admin/webhook_endpoints_created.html.erb +9 -0
  41. data/lib/generators/open_loam/install/templates/admin/webhook_endpoints_index.html.erb +8 -6
  42. data/lib/generators/open_loam/install/templates/admin/webhook_endpoints_new.html.erb +2 -2
  43. data/lib/generators/open_loam/install/templates/api_base_controller.rb +43 -6
  44. data/lib/generators/open_loam/install/templates/import_job.rb +14 -1
  45. data/lib/generators/open_loam/install/templates/initializer.rb +14 -2
  46. data/lib/generators/open_loam/install/templates/migrations/create_open_loam_api_tokens.rb +2 -2
  47. data/lib/generators/open_loam/install/templates/migrations/create_open_loam_event_records.rb +13 -0
  48. data/lib/generators/open_loam/install/templates/migrations/create_open_loam_inbound_webhooks.rb +0 -1
  49. data/lib/generators/open_loam/install/templates/migrations/create_open_loam_sso_providers.rb +3 -0
  50. data/lib/generators/open_loam/install/templates/migrations/create_open_loam_webhook_deliveries.rb +29 -0
  51. data/lib/generators/open_loam/install/templates/migrations/create_open_loam_webhook_endpoints.rb +12 -2
  52. data/lib/open_loam/auth_throttle.rb +11 -3
  53. data/lib/open_loam/custom_field_index.rb +11 -8
  54. data/lib/open_loam/encryptable.rb +8 -3
  55. data/lib/open_loam/encryption/key_provider.rb +17 -1
  56. data/lib/open_loam/encryption.rb +47 -4
  57. data/lib/open_loam/engine.rb +14 -0
  58. data/lib/open_loam/errors.rb +10 -0
  59. data/lib/open_loam/event_log.rb +77 -0
  60. data/lib/open_loam/export.rb +6 -6
  61. data/lib/open_loam/import.rb +1 -4
  62. data/lib/open_loam/inbound_webhooks.rb +12 -11
  63. data/lib/open_loam/lifecycle.rb +29 -0
  64. data/lib/open_loam/mcp.rb +10 -1
  65. data/lib/open_loam/outbound_url.rb +120 -0
  66. data/lib/open_loam/policy.rb +16 -3
  67. data/lib/open_loam/search/token_driver.rb +1 -1
  68. data/lib/open_loam/sso/http_client.rb +15 -6
  69. data/lib/open_loam/sso.rb +23 -2
  70. data/lib/open_loam/version.rb +1 -1
  71. data/lib/open_loam/webhooks/http_transport.rb +76 -0
  72. data/lib/open_loam/webhooks.rb +271 -17
  73. data/lib/open_loam.rb +3 -0
  74. data/lib/tasks/open_loam.rake +32 -0
  75. metadata +12 -2
@@ -1,26 +1,145 @@
1
1
  module OpenLoam
2
- # Where one tenant wants its domain events delivered. `event_pattern` uses
3
- # the same rule as OpenLoam::Events.subscribe — a trailing dot is a domain prefix
4
- # ("rental."), anything else is an exact event name.
2
+ # Where one tenant wants its domain events delivered. A pattern uses the rule
3
+ # shared with OpenLoam::Events.subscribe: a trailing dot is a domain prefix
4
+ # ("rental."), anything else is an exact event name. `event_pattern` is the
5
+ # 0.3.0 single pattern; `event_patterns` holds several.
5
6
  #
6
- # The secret signs every delivery (X-OpenLoam-Signature), so a receiver can tell
7
- # a real call from a forged one.
7
+ # The secret signs every delivery. With OpenLoam::Webhooks.encrypt_secrets on,
8
+ # it is sealed with the tenant's key (OpenLoam::Encryption, "v2:..."); rows
9
+ # written before that stay readable as plaintext.
10
+ #
11
+ # `metadata` belongs to the host app (e.g. which fields a receiver may see);
12
+ # OpenLoam stores it and never reads it.
8
13
  class WebhookEndpoint < OpenLoam::TenantRecord
9
14
  self.table_name = "open_loam_webhook_endpoints"
10
15
 
11
- validates :url, presence: true, format: { with: %r{\Ahttps?://}, message: "must start with http:// or https://" }
12
- validates :event_pattern, presence: true
16
+ SEALED_PREFIXES = %w[v1: v2:].freeze
17
+
18
+ has_many :deliveries, class_name: "OpenLoam::WebhookDelivery", foreign_key: :endpoint_id,
19
+ inverse_of: :endpoint, dependent: :delete_all
20
+
21
+ validates :url, presence: true
22
+ validate :at_least_one_pattern
23
+ # The server fetches this URL, so a tenant must not aim it at an address only
24
+ # the server can reach. Shape is checked at save; the delivery re-checks with
25
+ # DNS, because DNS moves.
26
+ validate :url_is_reachable_from_outside, if: -> { url.present? }
13
27
 
14
28
  scope :active, -> { where(active: true) }
15
29
 
16
30
  before_validation on: :create do
17
- self.secret ||= SecureRandom.hex(32)
31
+ self.secret = self.class.generate_secret if read_attribute(:secret).blank?
32
+ end
33
+
34
+ def self.generate_secret = SecureRandom.hex(32)
35
+
36
+ def patterns
37
+ list = Array(self[:event_patterns]).map(&:to_s).reject(&:empty?)
38
+ list.empty? ? [ event_pattern.to_s ].reject(&:empty?) : list
18
39
  end
19
40
 
20
- # One matcher, shared with the event bus, so "rental." means the same thing
21
- # to a subscriber and to a webhook.
22
41
  def matches?(event_name)
23
- OpenLoam::Events.pattern_matches?(event_pattern, event_name)
42
+ patterns.any? { |pattern| OpenLoam::Events.pattern_matches?(pattern, event_name) }
43
+ end
44
+
45
+ def settings
46
+ value = self[:metadata]
47
+ value = JSON.parse(value) if value.is_a?(String)
48
+ (value || {}).to_h.stringify_keys
49
+ end
50
+
51
+ def secret = unseal(read_attribute(:secret), "secret")
52
+ def secret=(value)
53
+ write_attribute(:secret, seal(value, "secret"))
54
+ end
55
+
56
+ def previous_secret = unseal(read_attribute(:previous_secret), "previous_secret")
57
+ def previous_secret=(value)
58
+ write_attribute(:previous_secret, seal(value, "previous_secret"))
59
+ end
60
+
61
+ # The secrets a delivery is signed with right now: the current one, plus the
62
+ # previous one while its grace period runs, so receivers can switch over.
63
+ def signing_secrets(now = Time.current)
64
+ keep_previous = previous_secret_expires_at && previous_secret_expires_at > now
65
+ [ secret, (previous_secret if keep_previous) ].compact
66
+ end
67
+
68
+ def rotate_secret!(now: Time.current)
69
+ new_secret = self.class.generate_secret
70
+ update!(previous_secret: secret, previous_secret_expires_at: now + OpenLoam::Webhooks.secret_rotation_grace,
71
+ secret: new_secret)
72
+ new_secret
73
+ end
74
+
75
+ def record_success!(at = Time.current)
76
+ update_columns(consecutive_failures: 0, failing_since: nil, last_success_at: at, updated_at: at)
77
+ end
78
+
79
+ # SQL increment, so two failing deliveries at once still count twice.
80
+ # Disabled only when the streak is both long (disable_after_failures) and
81
+ # old (failing_since at least disable_after_duration ago): a busy endpoint
82
+ # can rack up many failures during a short outage and should survive it.
83
+ def record_failure!(at = Time.current)
84
+ self.class.where(id: id).update_all([ "consecutive_failures = consecutive_failures + 1, " \
85
+ "failing_since = COALESCE(failing_since, ?), last_failure_at = ?, updated_at = ?",
86
+ at, at, at ])
87
+ reload
88
+ disable!("consecutive_failures") if failing_long_enough?(at)
89
+ end
90
+
91
+ # Idempotent and race-safe: only the caller whose UPDATE flips the row from
92
+ # on to off publishes the event.
93
+ def disable!(reason)
94
+ flipped = self.class.where(id: id, active: true)
95
+ .update_all(active: false, disabled_reason: reason.to_s, updated_at: Time.current) == 1
96
+ return unless flipped
97
+
98
+ reload
99
+ OpenLoam::Events.publish(OpenLoam::Webhooks::DISABLED_EVENT, { endpoint_id: id, reason: reason.to_s })
100
+ end
101
+
102
+ def enable!
103
+ update!(active: true, disabled_reason: nil, consecutive_failures: 0, failing_since: nil)
104
+ end
105
+
106
+ private
107
+
108
+ def failing_long_enough?(at)
109
+ limit = OpenLoam::Webhooks.disable_after_failures
110
+ return false unless limit && consecutive_failures >= limit
111
+
112
+ duration = OpenLoam::Webhooks.disable_after_duration
113
+ duration.nil? || (failing_since && failing_since <= at - duration)
114
+ end
115
+
116
+ def at_least_one_pattern
117
+ errors.add(:event_pattern, :blank) if patterns.empty?
118
+ end
119
+
120
+ def url_is_reachable_from_outside
121
+ OpenLoam::OutboundUrl.validate!(url, require_https: OpenLoam::Webhooks.require_https?,
122
+ ports: OpenLoam::Webhooks.allowed_ports)
123
+ rescue OpenLoam::OutboundUrl::BlockedError => error
124
+ errors.add(:url, error.message)
125
+ end
126
+
127
+ def key_scope = "tenant/#{tenant_id || OpenLoam.tenant!.id}"
128
+
129
+ def seal(value, column)
130
+ return value if value.nil? || !OpenLoam::Webhooks.encrypt_secrets?
131
+
132
+ OpenLoam::Encryption.encrypt_scoped(value, key_scope,
133
+ aad: OpenLoam::Encryption.aad(key_scope, self.class.table_name, column))
134
+ end
135
+
136
+ # A hex secret never contains ":", so anything without a version tag is a
137
+ # plaintext row from before encryption was switched on.
138
+ def unseal(stored, column)
139
+ return stored if stored.nil? || SEALED_PREFIXES.none? { |prefix| stored.start_with?(prefix) }
140
+
141
+ OpenLoam::Encryption.decrypt_scoped(stored, key_scope,
142
+ aad: OpenLoam::Encryption.aad(key_scope, self.class.table_name, column))
24
143
  end
25
144
  end
26
145
  end
@@ -3,6 +3,10 @@
3
3
  rendering lives once in the gem instead of being inlined per entity. %>
4
4
  <% mode = local_assigns.fetch(:mode, :edit) %>
5
5
  <% record.class.custom_field_definitions.each do |definition| %>
6
+ <%# Not readable by this role: omit the field entirely. Falling through to the
7
+ read-only branch below would print the value to anyone who merely lacks
8
+ WRITE access, which is a different question. %>
9
+ <% next unless policy.custom_field_readable?(definition.name) %>
6
10
  <% param_name = "#{record.model_name.param_key}[custom_fields][#{definition.name}]" %>
7
11
  <% value = record.custom_field(definition.name) %>
8
12
  <p>
@@ -8,6 +8,7 @@ module Api
8
8
  before_action :set_record, only: %i[show update destroy]
9
9
 
10
10
  def index
11
+ authorize!(policy_for(<%= class_name %>.new), :read?)
11
12
  records = <%= class_name %>.order(created_at: :desc).to_a
12
13
  enriched = OpenLoam::Enrichers.enrich_many(records) # one batched pass, no N+1
13
14
  render json: records.map { |record| entity_json(record, enrichments: enriched[record.id]) }
@@ -15,6 +15,7 @@ module Admin
15
15
  end
16
16
 
17
17
  def index
18
+ authorize!(policy_for(<%= class_name %>.new), :read?)
18
19
  @perspective = OpenLoam::Perspectives.resolve("<%= class_name %>", user: current_actor, id: params[:perspective_id])
19
20
  @perspectives = OpenLoam::Perspectives.visible_to("<%= class_name %>", user: current_actor)
20
21
  @records, @page, @has_next = paginate(index_scope)
@@ -32,6 +33,10 @@ module Admin
32
33
  # Datatable bulk actions on the selected ids — each is policy-checked per
33
34
  # record and tenant-scoped (OpenLoam::Bulk). Zero selection is a no-op.
34
35
  def bulk
36
+ # OpenLoam::Bulk checks the policy PER record (destroy? for soft_delete,
37
+ # update? + writable? for set_field) and silently skips what the actor may
38
+ # not touch, so the authorization is real — it just lives there, not here.
39
+ authorized!
35
40
  ids = Array(params[:ids])
36
41
  case params[:bulk_action]
37
42
  when "soft_delete"
@@ -147,9 +152,14 @@ module Admin
147
152
  # against real columns (never interpolated from params — that would be SQL
148
153
  # injection), and the direction is constrained to asc/desc. With no valid
149
154
  # sort param, a perspective's own order is kept, else a stable default.
155
+ #
156
+ # It must also be a column the role may READ: ordering by a hidden field
157
+ # leaks its ordering, which is an inference oracle on a value the role
158
+ # cannot see. Same reasoning as OpenLoam::FieldAccessError on custom fields —
159
+ # ignored rather than raised, since the header is not rendered either.
150
160
  def apply_sort(scope)
151
161
  column = params[:sort].to_s
152
- if <%= class_name %>.column_names.include?(column)
162
+ if <%= class_name %>.column_names.include?(column) && policy_for(<%= class_name %>.new).readable?(column)
153
163
  dir = params[:dir].to_s.casecmp("asc").zero? ? :asc : :desc
154
164
  scope.reorder(column => dir).order(id: dir)
155
165
  elsif scope.order_values.empty?
@@ -36,13 +36,16 @@
36
36
  </ul>
37
37
  <%% end %>
38
38
 
39
+ <%%# Three states per field: writable (input), readable-only (shown, labelled
40
+ read-only), or neither (absent). There is no branch for the third case on
41
+ purpose — a field the role may not read is not rendered at all. %>
39
42
  <% attributes.each do |attribute| -%>
40
43
  <%% if policy.writable?(:<%= attribute.name %>) %>
41
44
  <p>
42
45
  <%%= f.label :<%= attribute.name %> %><br>
43
46
  <%%= f.<%= form_field_helper(attribute) %> :<%= attribute.name %> %>
44
47
  </p>
45
- <%% else %>
48
+ <%% elsif policy.readable?(:<%= attribute.name %>) %>
46
49
  <p>
47
50
  <%%= f.label :<%= attribute.name %> %>: <%%= @record.<%= attribute.name %> %>
48
51
  <em><%%= t("open_loam.form.read_only") %></em>
@@ -1,3 +1,7 @@
1
+ <%%# One policy for the whole table: readable? keys off the actor's ROLE, not the
2
+ row, so building it per record would only add a membership query per row. %>
3
+ <%% policy = OpenLoam::Policy.for_model(<%= class_name %>, current_actor) %>
4
+
1
5
  <h1><%%= <%= class_name %>.model_name.human(count: 2) %></h1>
2
6
 
3
7
  <%% if @index_partial %>
@@ -55,7 +59,7 @@
55
59
  <th><input type="checkbox" onclick="document.querySelectorAll('.bulk-select').forEach(function(c){c.checked=this.checked}.bind(this))"></th>
56
60
  <th><%%= t("open_loam.labels.id") %></th>
57
61
  <% attributes.each do |attribute| -%>
58
- <th><%%= sort_link("<%= attribute.name %>", <%= class_name %>.human_attribute_name("<%= attribute.name %>")) %></th>
62
+ <%% if policy.readable?(:<%= attribute.name %>) %><th><%%= sort_link("<%= attribute.name %>", <%= class_name %>.human_attribute_name("<%= attribute.name %>")) %></th><%% end %>
59
63
  <% end -%>
60
64
  <th></th>
61
65
  </tr>
@@ -66,7 +70,7 @@
66
70
  <td><%%= check_box_tag "ids[]", record.id, false, class: "bulk-select" %></td>
67
71
  <td><%%= record.id %></td>
68
72
  <% attributes.each do |attribute| -%>
69
- <td><%%= record.<%= attribute.name %> %></td>
73
+ <%% if policy.readable?(:<%= attribute.name %>) %><td><%%= record.<%= attribute.name %> %></td><%% end %>
70
74
  <% end -%>
71
75
  <td>
72
76
  <%%= link_to t("open_loam.actions.show"), [:admin, record] %>
@@ -3,7 +3,9 @@
3
3
  <h1><%%= t("open_loam.actions.show_title", name: <%= class_name %>.model_name.human, id: @record.id) %></h1>
4
4
 
5
5
  <% attributes.each do |attribute| -%>
6
+ <%% if policy.readable?(:<%= attribute.name %>) %>
6
7
  <p><strong><%%= <%= class_name %>.human_attribute_name("<%= attribute.name %>") %>:</strong> <%%= @record.<%= attribute.name %> %></p>
8
+ <%% end %>
7
9
  <% end -%>
8
10
 
9
11
  <%%= render "open_loam/custom_fields/fields", record: @record, policy: policy, mode: :show %>
@@ -42,7 +42,9 @@ module OpenLoam
42
42
  migration_template "migrations/create_open_loam_auth_attempts.rb", "db/migrate/create_open_loam_auth_attempts.rb"
43
43
  migration_template "migrations/create_open_loam_custom_field_values.rb", "db/migrate/create_open_loam_custom_field_values.rb"
44
44
  migration_template "migrations/create_open_loam_event_deliveries.rb", "db/migrate/create_open_loam_event_deliveries.rb"
45
+ migration_template "migrations/create_open_loam_event_records.rb", "db/migrate/create_open_loam_event_records.rb"
45
46
  migration_template "migrations/create_open_loam_inbound_webhooks.rb", "db/migrate/create_open_loam_inbound_webhooks.rb"
47
+ migration_template "migrations/create_open_loam_webhook_deliveries.rb", "db/migrate/create_open_loam_webhook_deliveries.rb"
46
48
  end
47
49
 
48
50
  # Attachments (OpenLoam::Attachable, included in every generated entity) are
@@ -69,6 +71,16 @@ module OpenLoam
69
71
  template "initializer.rb", "config/initializers/open_loam.rb"
70
72
  end
71
73
 
74
+ # Rails' default filter list covers passwords and tokens but not the params
75
+ # OpenLoam introduces: an uploaded :csv is a payload of real records, and
76
+ # :code is a live TOTP.
77
+ def filter_open_loam_parameters
78
+ append_to_file "config/initializers/filter_parameter_logging.rb", <<~RUBY
79
+
80
+ Rails.application.config.filter_parameters += %i[csv file code recovery secret otp]
81
+ RUBY
82
+ end
83
+
72
84
  def create_agents_md
73
85
  template "AGENTS.md", "AGENTS.md"
74
86
  end
@@ -124,6 +136,7 @@ module OpenLoam
124
136
  template "admin/notifications_index.html.erb", "app/views/admin/notifications/index.html.erb"
125
137
  template "admin/webhook_endpoints_index.html.erb", "app/views/admin/webhook_endpoints/index.html.erb"
126
138
  template "admin/webhook_endpoints_new.html.erb", "app/views/admin/webhook_endpoints/new.html.erb"
139
+ template "admin/webhook_endpoints_created.html.erb", "app/views/admin/webhook_endpoints/created.html.erb"
127
140
  template "admin/api_tokens_index.html.erb", "app/views/admin/api_tokens/index.html.erb"
128
141
  template "admin/configs_index.html.erb", "app/views/admin/configs/index.html.erb"
129
142
  template "admin/configs_edit.html.erb", "app/views/admin/configs/edit.html.erb"
@@ -54,7 +54,7 @@ the gotchas in the framework itself.
54
54
  | Attachments | ActiveStorage `files` via `OpenLoam::Attachable` | `record.files.attach(...)`, or the file field on the entity's form — uploading counts as an update, so the entity's policy decides |
55
55
  | Sign-in | `app/controllers/admin/sessions_controller.rb` (`has_secure_password` on `User`) | email + password, then a tenant — the picker only ever lists tenants you hold a `OpenLoam::Membership` in |
56
56
  | JSON API | `app/controllers/api/<plural>_controller.rb` | generated with the entity; auth is `Authorization: Bearer <OpenLoam::ApiToken>`, and the same policies apply |
57
- | Webhooks (outbound) | `OpenLoam::WebhookEndpoint` rows, managed at `/admin/webhook_endpoints` | add an endpoint with an event pattern; matching events POST signed JSON via `OpenLoam::WebhookDeliveryJob` |
57
+ | Webhooks (outbound) | `OpenLoam::WebhookEndpoint` rows, managed at `/admin/webhook_endpoints` | add an endpoint with an event pattern; each matching event writes an `OpenLoam::WebhookDelivery` ledger row, POSTed signed JSON via `OpenLoam::WebhookDeliveryJob` and retried; apps not ticking `OpenLoam::Scheduler` must schedule `OpenLoam::WebhookSweepJob` every minute |
58
58
  | Webhooks (inbound) | `OpenLoam::InboundWebhookSource` at `/admin/inbound_webhook_sources`; public `POST /webhooks/:token` | register a source (token+secret generated); external systems POST HMAC-signed bodies; verified, replay-deduped, published on the bus as the source's `event_name` — a durable subscriber reads the body from `OpenLoam::InboundWebhookDelivery` ([details](https://github.com/DeliveristsIO/open-loam/blob/main/docs/_agents/inbound-webhooks.md)) |
59
59
  | Tests | `test/entities/<name>_test.rb` | generated with the entity; extend, never delete |
60
60
  | New-tenant defaults | `OpenLoam.on_tenant_created` blocks in `config/initializers/open_loam.rb` | edit the initializer; backfill with `bin/rails open_loam:sync` |
@@ -307,7 +307,11 @@ So the block MUST be idempotent — `find_or_create_by!`, never `create!`.
307
307
  `OpenLoam::FieldDefinition` doesn't exist — create it, don't swallow the error.
308
308
  - **Never write raw SQL that touches tenant tables** without a `tenant_id` predicate.
309
309
  - **Every controller action checks a policy** (`authorize!`); every form uses
310
- `policy.permitted_fields` — no hand-rolled `params.permit` lists.
310
+ `policy.permitted_fields` — no hand-rolled `params.permit` lists. This is
311
+ ENFORCED: an action that authorizes nothing raises
312
+ `OpenLoam::AuthorizationNotPerformedError` after it runs. If a screen really is
313
+ authorized structurally, say so with `skip_authorization! "<reason>"` — never
314
+ add a token `authorize!` to quiet the guard.
311
315
  - **Event names are `domain.thing.happened`** — three+ dot-separated segments.
312
316
  - **`OpenLoam.on_tenant_created` callbacks are idempotent** — `open_loam:sync` re-runs them.
313
317
  - **Never assign a workflow column directly** — call the transition, so the legal
@@ -1,23 +1,37 @@
1
1
  module Admin
2
- # Your own API tokens, and only ever your own: every query is scoped to
3
- # current_actor, so there is no path to another user's credentials. A token
4
- # acts as its user in this tenant, which is precisely why nobody else may
5
- # list, create or revoke one for you.
2
+ # Your own API tokens — creating and listing is scoped to current_actor, so
3
+ # there is no path to another user's credentials. Revoking is the exception: a
4
+ # manager owns offboarding, and a token that outlives someone's access is the
5
+ # thing offboarding is supposed to end.
6
6
  class ApiTokensController < BaseController
7
+ skip_authorization! "Scoped to current_actor; the manager-wide revoke path calls require_role! itself."
8
+
9
+ # Revoking an API token cuts off a machine's access — sensitive enough to
10
+ # re-confirm, even for a manager (step-up is orthogonal to role).
11
+ before_action :require_sudo!, only: :destroy
12
+
7
13
  def index
8
14
  @records = api_tokens.order(created_at: :desc)
15
+ # Only the label, owner and usage — never a token value, which no longer
16
+ # exists in a readable form anyway.
17
+ @tenant_records = manager? ? OpenLoam::ApiToken.where.not(user_id: current_actor.id).order(created_at: :desc) : []
9
18
  end
10
19
 
11
20
  def create
12
21
  token = api_tokens.create!(label: params[:label].presence || "API token")
13
22
 
14
- # Shown once, on the next screen — the habit that matters when tokens
15
- # are eventually stored hashed rather than in the clear.
23
+ # The only time the plaintext exists: only its digest is stored, so this
24
+ # screen is genuinely the last chance to copy it.
16
25
  redirect_to admin_api_tokens_path, flash: { token: token.token }
17
26
  end
18
27
 
19
28
  def destroy
20
- api_tokens.find(params[:id]).destroy!
29
+ # Tenant-scoped by the default scope, so another tenant's token is not
30
+ # merely forbidden here — it is not findable.
31
+ record = OpenLoam::ApiToken.find(params[:id])
32
+ require_role!(:manager) unless record.user_id == current_actor.id
33
+
34
+ record.destroy!
21
35
  redirect_to admin_api_tokens_path
22
36
  end
23
37
 
@@ -26,5 +40,9 @@ module Admin
26
40
  def api_tokens
27
41
  OpenLoam::ApiToken.where(user_id: current_actor.id)
28
42
  end
43
+
44
+ def manager?
45
+ current_role == :manager
46
+ end
29
47
  end
30
48
  end
@@ -37,3 +37,26 @@ audit trail. Send it as <code>Authorization: Bearer &lt;token&gt;</code>.</p>
37
37
  <%% end %>
38
38
  </tbody>
39
39
  </table>
40
+
41
+ <%% if @tenant_records.any? %>
42
+ <h2>Everyone else's tokens</h2>
43
+ <p>Manager view. Removing someone's membership already stops their tokens
44
+ working; revoking is the clean end of it.</p>
45
+
46
+ <table>
47
+ <thead>
48
+ <tr><th>Owner</th><th>Label</th><th>Created</th><th>Last used</th><th></th></tr>
49
+ </thead>
50
+ <tbody>
51
+ <%% @tenant_records.each do |record| %>
52
+ <tr>
53
+ <td><%%= record.user.name %></td>
54
+ <td><%%= record.label %></td>
55
+ <td><%%= record.created_at.to_fs(:short) %></td>
56
+ <td><%%= record.last_used_at&.to_fs(:short) || "never" %></td>
57
+ <td><%%= button_to "Revoke", admin_api_token_path(record), method: :delete, form: { style: "display:inline" } %></td>
58
+ </tr>
59
+ <%% end %>
60
+ </tbody>
61
+ </table>
62
+ <%% end %>
@@ -5,8 +5,28 @@ module Admin
5
5
  layout "admin"
6
6
 
7
7
  before_action :set_open_loam_context
8
+ before_action :require_mfa_enrollment!
8
9
  before_action :set_locale
9
10
 
11
+ # Fails an action that never authorized anything. Forgetting `authorize!` is
12
+ # otherwise silent — the screen renders, and nothing says the policy was
13
+ # never consulted.
14
+ #
15
+ # It runs AFTER the action, so it catches the omission in development and in
16
+ # tests; it is not a runtime access-control layer. A `destroy` that forgot to
17
+ # authorize has already destroyed the record by the time this raises.
18
+ after_action :verify_authorized!
19
+
20
+ # For screens that are authorized STRUCTURALLY rather than by a policy call —
21
+ # a list scoped to current_actor, a pre-auth screen. The reason is required
22
+ # and shows up in the source, so every exemption is a documented claim rather
23
+ # than a silent opt-out.
24
+ def self.skip_authorization!(reason, **options)
25
+ raise ArgumentError, "skip_authorization! needs a reason" if reason.to_s.strip.empty?
26
+
27
+ skip_after_action :verify_authorized!, **options
28
+ end
29
+
10
30
  rescue_from OpenLoam::NotAuthorizedError do
11
31
  render plain: "403 Forbidden — your role does not permit this action.", status: :forbidden
12
32
  end
@@ -86,6 +106,22 @@ module Admin
86
106
  OpenLoam::Membership.exists?(user_id: current_actor.id)
87
107
  end
88
108
 
109
+ # security.mfa_required_roles has to hold on EVERY request, not just as a
110
+ # redirect at the end of login — otherwise typing any other admin URL walks
111
+ # straight past enrollment and the requirement means nothing.
112
+ def require_mfa_enrollment!
113
+ return if OpenLoam::MfaCredential.active_for(current_actor)
114
+ return unless mfa_required_role?
115
+
116
+ redirect_to new_admin_mfa_path,
117
+ alert: "Your role requires two-factor authentication — set it up to continue."
118
+ end
119
+
120
+ def mfa_required_role?
121
+ required = Array(OpenLoam::Configs.get("security.mfa_required_roles", default: []))
122
+ required.map(&:to_s).include?(current_role.to_s)
123
+ end
124
+
89
125
  # Drives the bell in the admin layout. One COUNT per admin page render,
90
126
  # which is fine at this scale; cache it if a screen ever gets hot.
91
127
  def unread_notification_count
@@ -106,9 +142,30 @@ module Admin
106
142
  end
107
143
 
108
144
  def authorize!(policy, action)
145
+ authorized!
109
146
  raise OpenLoam::NotAuthorizedError unless policy.public_send(action)
110
147
  end
111
148
 
149
+ # Records that this action asked a person-authorization question — marked
150
+ # whether the answer was yes or no, since a refusal is still a check.
151
+ #
152
+ # Call it directly only where the check is an inline `raise` rather than one
153
+ # of the helpers below (see Admin::PerspectivesController). Deliberately NOT
154
+ # called by require_feature! (a capability gate, not a person gate) or
155
+ # require_sudo! (step-up, orthogonal to role) — either marking the action
156
+ # would let a feature-gated screen skip authorization silently.
157
+ def authorized!
158
+ @open_loam_authorized = true
159
+ end
160
+
161
+ def verify_authorized!
162
+ return if @open_loam_authorized
163
+
164
+ raise OpenLoam::AuthorizationNotPerformedError,
165
+ "#{self.class.name}##{action_name} finished without authorizing. Call authorize!/require_role!/" \
166
+ "require_permission!, or declare `skip_authorization! \"<why>\"` if it is authorized structurally."
167
+ end
168
+
112
169
  # For admin screens with no per-record policy (e.g. field definitions,
113
170
  # which apply to a whole entity_type rather than one record).
114
171
  def current_role
@@ -116,6 +173,7 @@ module Admin
116
173
  end
117
174
 
118
175
  def require_role!(*roles)
176
+ authorized!
119
177
  raise OpenLoam::NotAuthorizedError unless roles.include?(current_role)
120
178
  end
121
179
 
@@ -127,6 +185,7 @@ module Admin
127
185
  end
128
186
 
129
187
  def require_permission!(permission)
188
+ authorized!
130
189
  raise OpenLoam::NotAuthorizedError unless OpenLoam.can?(permission)
131
190
  end
132
191
 
@@ -153,6 +212,10 @@ module Admin
153
212
  # be a false conflict every time.
154
213
  def stale_conflict!(record, fields)
155
214
  encrypted = record.class.respond_to?(:open_loam_encrypted_attributes) ? record.class.open_loam_encrypted_attributes.map(&:to_s) : []
215
+ # The diff shows the OTHER person's saved values, so it obeys the same field
216
+ # rules as any other read. Anything not writable was never submitted anyway.
217
+ policy = policy_for(record)
218
+ fields = fields.select { |field| policy.writable?(field) && policy.readable?(field) }
156
219
  attempted = fields.map(&:to_s).index_with { |field| conflict_value(record, field, encrypted) }
157
220
 
158
221
  record.reload
@@ -1,5 +1,7 @@
1
1
  module Admin
2
2
  class DashboardController < BaseController
3
+ skip_authorization! "Widgets are filtered by role in OpenLoam::Dashboard.for; there is no per-record subject."
4
+
3
5
  def index
4
6
  # Configurable, role-visible widgets (OpenLoam::Dashboard) — a raising widget
5
7
  # is isolated into an error tile, never breaking the page. Register your
@@ -7,6 +7,8 @@ module Admin
7
7
  # committed and there is no going back; that ordering is the whole safety of a
8
8
  # Live action.
9
9
  class EventsController < BaseController
10
+ skip_authorization! "OpenLoam::EventStream gates every message: declared pattern, matching tenant, and audience."
11
+
10
12
  include ActionController::Live
11
13
 
12
14
  HEARTBEAT_SECONDS = 20
@@ -6,6 +6,8 @@ module Admin
6
6
  class HistoryController < BaseController
7
7
  before_action :set_target
8
8
 
9
+ helper_method :visible_changeset
10
+
9
11
  def index
10
12
  authorize!(policy_for(@record), :read?)
11
13
  @audits = OpenLoam::AuditRecord
@@ -24,6 +26,30 @@ module Admin
24
26
 
25
27
  private
26
28
 
29
+ # History is a read path like any other: a field the role may not read must
30
+ # not come back here as an old → new pair.
31
+ def visible_changeset(audit)
32
+ policy = (@history_policy ||= policy_for(@record))
33
+
34
+ (audit.changeset || {}).each_with_object({}) do |(field, values), visible|
35
+ if field == "custom_fields"
36
+ readable = readable_custom_fields(values, policy)
37
+ visible[field] = readable if readable
38
+ elsif policy.readable?(field)
39
+ visible[field] = values
40
+ end
41
+ end
42
+ end
43
+
44
+ # Runtime fields are audited as one json blob, so the filter goes inside the
45
+ # old/new pair rather than dropping the whole entry.
46
+ def readable_custom_fields(values, policy)
47
+ return values unless values.is_a?(Array)
48
+
49
+ sides = values.map { |side| side.to_h.select { |name, _| policy.custom_field_readable?(name) } }
50
+ sides.any?(&:present?) ? sides : nil
51
+ end
52
+
27
53
  # The target record, looked up through its OWN default scope (tenancy holds;
28
54
  # a soft-deleted row is still reachable to restore). The type is whitelisted
29
55
  # to a OpenLoam::TenantRecord — never a bare constantize of a param.
@@ -18,7 +18,7 @@ never reverted here.</p>
18
18
  <td><code><%%= audit.action %></code></td>
19
19
  <td><%%= audit.actor&.name || "—" %></td>
20
20
  <td>
21
- <%% (audit.changeset || {}).each do |field, values| %>
21
+ <%% visible_changeset(audit).each do |field, values| %>
22
22
  <div><code><%%= field %></code>:
23
23
  <%%= values.is_a?(Array) ? "#{values.first.inspect} → #{values.last.inspect}" : values %></div>
24
24
  <%% end %>
@@ -31,7 +31,7 @@ module Admin
31
31
  if params[:commit] == "Dry run"
32
32
  run_dry(mapping, match_key)
33
33
  else
34
- ImportJob.perform_later(entity_type: @entity_type, csv: @csv, mapping: mapping,
34
+ ImportJob.perform_later(entity_type: @entity_type, blob_id: staged_csv_blob(@csv).id, mapping: mapping,
35
35
  match_key: match_key, tenant_id: current_tenant.id, actor_id: current_actor.id)
36
36
  redirect_to admin_progress_jobs_path, notice: "Import started — watch it progress under Tasks."
37
37
  end
@@ -71,5 +71,17 @@ module Admin
71
71
 
72
72
  file.read.force_encoding("UTF-8")
73
73
  end
74
+
75
+ # The CSV goes to blob storage and the JOB gets an id. ActiveJob arguments
76
+ # are serialized into the queue backend and echoed in the job log, so
77
+ # passing the file itself would leave every row sitting in the clear —
78
+ # including the columns headed for encrypted fields. ImportJob purges it.
79
+ def staged_csv_blob(csv)
80
+ ActiveStorage::Blob.create_and_upload!(
81
+ io: StringIO.new(csv),
82
+ filename: "#{@entity_type.underscore}-import-#{SecureRandom.hex(8)}.csv",
83
+ content_type: "text/csv"
84
+ )
85
+ end
74
86
  end
75
87
  end
@@ -53,7 +53,7 @@ module Admin
53
53
 
54
54
  def source_params
55
55
  params.require(:inbound_webhook_source).permit(
56
- :name, :event_name, :signature_header, :delivery_id_header,
56
+ :name, :event_name, :signature_header,
57
57
  :timestamp_header, :timestamp_tolerance
58
58
  )
59
59
  end
@@ -19,8 +19,6 @@
19
19
  <small>e.g. X-Hub-Signature-256 for GitHub.</small>
20
20
  </p>
21
21
  <p>
22
- <%%= f.label :delivery_id_header, "Delivery-id header (optional, for dedupe)" %><br>
23
- <%%= f.text_field :delivery_id_header %>
24
22
  <small>Blank = dedupe on a hash of the body.</small>
25
23
  </p>
26
24
  <p>
@@ -6,6 +6,11 @@ module Admin
6
6
  # old secret stays valid until the new one is proven — so neither a cross-site
7
7
  # GET nor an abandoned re-enrollment can downgrade an active credential.
8
8
  class MfaController < BaseController
9
+ skip_authorization! "Your own MFA credentials; sensitive changes go through require_sudo! instead."
10
+
11
+ # This IS the enrollment screen the requirement sends people to.
12
+ skip_before_action :require_mfa_enrollment!
13
+
9
14
  # Shown in authenticator apps as the account issuer; defaults to the app name.
10
15
  ISSUER = Rails.application.class.module_parent_name.freeze
11
16