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
@@ -5,6 +5,8 @@ module Admin
5
5
  # OpenLoam::TenantRecord) and BaseController has already established that this
6
6
  # actor is signed in to this tenant. Recipient scoping is the whole rule.
7
7
  class NotificationsController < BaseController
8
+ skip_authorization! "Scoped to current_actor — there is no path to another user's notifications."
9
+
8
10
  def index
9
11
  @records = notifications.order(created_at: :desc).limit(100)
10
12
  end
@@ -8,6 +8,11 @@ module Admin
8
8
  # ones. A private view of someone else's is invisible here by construction
9
9
  # (OpenLoam::Perspectives.visible_to never returns it).
10
10
  class PerspectivesController < BaseController
11
+ # update/destroy/set_default authorize via authorize_manage!. index and create
12
+ # act only on the actor's own private views, so there is no subject to gate.
13
+ skip_authorization! "index lists views visible to the actor; create only ever makes a private one, owned by them.",
14
+ only: %i[index create]
15
+
11
16
  before_action :set_perspective, only: %i[update destroy set_default]
12
17
  before_action :authorize_manage!, only: %i[update destroy set_default]
13
18
 
@@ -68,6 +73,7 @@ module Admin
68
73
  end
69
74
 
70
75
  def authorize_manage!
76
+ authorized!
71
77
  raise OpenLoam::NotAuthorizedError unless can_manage?(@perspective)
72
78
  end
73
79
 
@@ -4,6 +4,9 @@ module Admin
4
4
  # Your app starts jobs with OpenLoam::Progress.start in its own background jobs;
5
5
  # a running one can be cancelled cooperatively here.
6
6
  class ProgressJobsController < BaseController
7
+ skip_authorization! "A tenant-scoped list of the tenant's own jobs; cancel is the gated action.",
8
+ only: :index
9
+
7
10
  def index
8
11
  @jobs = OpenLoam::ProgressJob.recent.limit(20)
9
12
  end
@@ -11,6 +14,7 @@ module Admin
11
14
  def cancel
12
15
  job = OpenLoam::ProgressJob.find(params[:id])
13
16
  # Manager-or-owner: a member must not cancel another user's job.
17
+ authorized!
14
18
  raise OpenLoam::NotAuthorizedError unless current_role == :manager || job.actor_id == current_actor&.id
15
19
  job.cancel! if job.running?
16
20
  redirect_to admin_progress_jobs_path, notice: "Job cancelled."
@@ -6,6 +6,8 @@ module Admin
6
6
  # tenant-scoped relation, so this can only ever find records the current
7
7
  # tenant owns.
8
8
  class SearchController < BaseController
9
+ skip_authorization! "Each model's `search` returns its own tenant-scoped relation; reads only."
10
+
9
11
  PER_ENTITY = 10
10
12
 
11
13
  helper_method :search_result_label
@@ -39,7 +39,8 @@ module Admin
39
39
  return render :new, status: :unauthorized
40
40
  end
41
41
 
42
- OpenLoam::AuthThrottle.clear(email) # a successful login resets the counter
42
+ # PASSWORD only — clearing every kind here would reset the TOTP counter.
43
+ OpenLoam::AuthThrottle.clear(email, kind: "password")
43
44
  reset_session # a fresh session id at login: no fixation
44
45
  session[:user_id] = user.id
45
46
 
@@ -58,8 +59,6 @@ module Admin
58
59
  @user = mfa_challenge_user or return redirect_to new_admin_session_path
59
60
  end
60
61
 
61
- # TODO (follow-up): rate-limit / lock out repeated failed codes here (needs
62
- # throttling infra) — a 6-digit TOTP is brute-forceable without it.
63
62
  def mfa_verify
64
63
  user = mfa_challenge_user or return redirect_to new_admin_session_path
65
64
 
@@ -74,7 +73,7 @@ module Admin
74
73
  credential = OpenLoam::MfaCredential.active_for(user)
75
74
 
76
75
  if credential.verify_totp(params[:code]) || credential.consume_recovery_code(params[:code])
77
- OpenLoam::AuthThrottle.clear(user.email)
76
+ OpenLoam::AuthThrottle.clear(user.email, kind: "totp")
78
77
  session.delete(:mfa_pending)
79
78
  complete_authentication(user)
80
79
  else
@@ -4,9 +4,15 @@
4
4
  below is sent to that identity provider to sign in (OIDC), and provisioned on
5
5
  first login. <%%= link_to "New provider", new_admin_sso_provider_path %></p>
6
6
 
7
+ <p>A provider does nothing until an operator confirms your organisation owns the
8
+ domain — anyone can type a domain here, so the claim has to be checked off the
9
+ admin path. Ask your operator to run
10
+ <code>rake open_loam:sso:verify_domain[&lt;id&gt;]</code>. Editing the domain
11
+ later clears the confirmation.</p>
12
+
7
13
  <table>
8
14
  <thead>
9
- <tr><th>Name</th><th>Protocol</th><th>Domain</th><th>JIT role</th><th>Active</th><th></th></tr>
15
+ <tr><th>Name</th><th>Protocol</th><th>Domain</th><th>Ownership</th><th>JIT role</th><th>Active</th><th></th></tr>
10
16
  </thead>
11
17
  <tbody>
12
18
  <%% @providers.each do |provider| %>
@@ -14,6 +20,7 @@ first login. <%%= link_to "New provider", new_admin_sso_provider_path %></p>
14
20
  <td><%%= provider.name %></td>
15
21
  <td><%%= provider.protocol %></td>
16
22
  <td><code><%%= provider.domain %></code></td>
23
+ <td><%%= provider.domain_verified? ? "confirmed" : "not confirmed — SSO is inactive" %></td>
17
24
  <td><%%= provider.jit_role %></td>
18
25
  <td><%%= provider.active? ? "yes" : "no" %></td>
19
26
  <td>
@@ -4,6 +4,8 @@ module Admin
4
4
  # (or TOTP code, if the user has MFA) stamps a fresh sudo timestamp and returns
5
5
  # to wherever they were headed.
6
6
  class SudoController < BaseController
7
+ skip_authorization! "The step-up re-challenge itself — authorizing it would require the sudo it grants."
8
+
7
9
  def new
8
10
  end
9
11
 
@@ -16,7 +18,7 @@ module Admin
16
18
  end
17
19
 
18
20
  if reauthenticated?
19
- OpenLoam::AuthThrottle.clear(identifier)
21
+ OpenLoam::AuthThrottle.clear(identifier, kind: "sudo")
20
22
  session[:sudo_at] = Time.now.to_i
21
23
  redirect_to(session.delete(:sudo_return_to).presence || admin_root_path,
22
24
  notice: "Re-authenticated — you can complete the action now.")
@@ -17,7 +17,10 @@ module Admin
17
17
  @record = OpenLoam::WebhookEndpoint.new(permitted_params)
18
18
 
19
19
  if @record.save
20
- redirect_to admin_webhook_endpoints_path
20
+ # The only screen that shows the secret: the receiver needs it to verify
21
+ # signatures, and it is never displayed again.
22
+ response.headers["Cache-Control"] = "no-store"
23
+ render :created, status: :created
21
24
  else
22
25
  render :new, status: :unprocessable_entity
23
26
  end
@@ -0,0 +1,9 @@
1
+ <h1>Webhook endpoint created</h1>
2
+
3
+ <p><strong>Copy the signing secret now.</strong> The receiver at
4
+ <code><%%= @record.url %></code> needs it to verify signatures. This is the only
5
+ time it is shown.</p>
6
+
7
+ <p><code><%%= @record.secret %></code></p>
8
+
9
+ <p><%%= link_to "Back to webhook endpoints", admin_webhook_endpoints_path %></p>
@@ -8,25 +8,27 @@ domain ("rental."); anything else is one exact event name.</p>
8
8
  <table>
9
9
  <thead>
10
10
  <tr>
11
- <th>Event pattern</th>
11
+ <th>Event patterns</th>
12
12
  <th>URL</th>
13
13
  <th>Active</th>
14
- <th>Secret</th>
14
+ <th>Status</th>
15
15
  <th></th>
16
16
  </tr>
17
17
  </thead>
18
18
  <tbody>
19
19
  <%% @records.each do |record| %>
20
20
  <tr>
21
- <td><%%= record.event_pattern %></td>
21
+ <td><%%= record.patterns.join(", ") %></td>
22
22
  <td><%%= record.url %></td>
23
23
  <td><%%= record.active? ? "yes" : "no" %></td>
24
- <td><code><%%= record.secret %></code></td>
24
+ <td><%%= record.active? ? "active" : "disabled (#{record.disabled_reason})" %></td>
25
25
  <td><%%= button_to "Delete", admin_webhook_endpoint_path(record), method: :delete, form: { style: "display:inline" } %></td>
26
26
  </tr>
27
27
  <%% end %>
28
28
  </tbody>
29
29
  </table>
30
30
 
31
- <p>Each delivery is signed: <code>X-OpenLoam-Signature: sha256=HMAC-SHA256(secret, body)</code>.
32
- Recompute it on your side and reject anything that does not match.</p>
31
+ <p>Each delivery is signed twice: <code>X-OpenLoam-Signature: sha256=HMAC-SHA256(secret, body)</code> (kept for
32
+ existing receivers) and <code>X-OpenLoam-Signature-V2: t=&lt;unix&gt;,v1=HMAC-SHA256(secret, "&lt;t&gt;.&lt;body&gt;")</code>,
33
+ which new receivers should verify. Read the secret with <code>OpenLoam::WebhookEndpoint#secret</code> in a console;
34
+ it is not shown here.</p>
@@ -1,6 +1,6 @@
1
1
  <h1>New webhook endpoint</h1>
2
2
 
3
- <%%= form_with model: @record, url: admin_webhook_endpoints_path do |f| %>
3
+ <%%= form_with model: @record, scope: :webhook_endpoint, url: admin_webhook_endpoints_path do |f| %>
4
4
  <%% if @record.errors.any? %>
5
5
  <ul>
6
6
  <%% @record.errors.full_messages.each do |message| %>
@@ -25,4 +25,4 @@
25
25
  <%%= f.submit "Create endpoint" %>
26
26
  <%% end %>
27
27
 
28
- <p>A signing secret is generated for you and shown on the list.</p>
28
+ <p>A signing secret is generated for you and shown once after you save.</p>
@@ -14,6 +14,17 @@ module Api
14
14
  class BaseController < ActionController::API
15
15
  before_action :authenticate_api_token!
16
16
 
17
+ # Same guard as the admin base controller: an endpoint that never authorized
18
+ # anything fails loudly rather than silently serving. Runs after the action,
19
+ # so it catches the omission in tests, not at runtime.
20
+ after_action :verify_authorized!
21
+
22
+ def self.skip_authorization!(reason, **options)
23
+ raise ArgumentError, "skip_authorization! needs a reason" if reason.to_s.strip.empty?
24
+
25
+ skip_after_action :verify_authorized!, **options
26
+ end
27
+
17
28
  rescue_from OpenLoam::NotAuthorizedError do
18
29
  render json: { error: "forbidden" }, status: :forbidden
19
30
  end
@@ -46,27 +57,53 @@ module Api
46
57
  end
47
58
 
48
59
  def authorize!(policy, action)
60
+ authorized!
49
61
  raise OpenLoam::NotAuthorizedError unless policy.public_send(action)
50
62
  end
51
63
 
52
- # The JSON shape of an entity: its columns, custom fields included (they
53
- # live in the `custom_fields` column that every generated entity carries).
64
+ # Marked whether the answer was yes or no — a refusal is still a check.
65
+ def authorized!
66
+ @open_loam_authorized = true
67
+ end
68
+
69
+ def verify_authorized!
70
+ return if @open_loam_authorized
71
+
72
+ raise OpenLoam::AuthorizationNotPerformedError,
73
+ "#{self.class.name}##{action_name} finished without authorizing. Call authorize!, or declare " \
74
+ "`skip_authorization! \"<why>\"` if it is authorized structurally."
75
+ end
76
+
77
+ # The JSON shape of an entity: the columns this actor's role may READ, plus
78
+ # the readable custom fields (which live in the `custom_fields` column that
79
+ # every generated entity carries).
80
+ #
81
+ # The read check is the same one the CSV export and the admin screens apply.
82
+ # Without it the API is a way around every `field readable:` rule in the app:
83
+ # the record is already loaded and `record.attributes` emits everything on it.
54
84
  #
55
85
  # Encrypted fields (OpenLoam::Encryptable) are returned DECRYPTED — the caller is
56
86
  # authenticated, tenant-scoped and policy-gated, exactly like the admin show
57
87
  # screen — and their blind-index `<field>_hash` column is dropped, so the
58
- # equality-leaking hash never goes over the wire. `record.attributes` alone
59
- # would emit the raw ciphertext plus the hash.
88
+ # equality-leaking hash never goes over the wire.
60
89
  def entity_json(record, enrichments: nil)
61
- json = record.attributes
90
+ policy = policy_for(record)
91
+ json = record.attributes.slice(*policy.readable_fields(record.attribute_names))
62
92
 
63
93
  if record.class.respond_to?(:open_loam_encrypted_attributes)
64
94
  record.class.open_loam_encrypted_attributes.each do |name|
65
- json[name] = record.public_send(name)
95
+ json[name] = record.public_send(name) if json.key?(name)
66
96
  json.delete("#{name}_hash")
67
97
  end
68
98
  end
69
99
 
100
+ # `custom_fields` is one JSON column, so it is all-or-nothing at the
101
+ # column level — filter its contents per definition instead.
102
+ if json.key?("custom_fields") && record.class.respond_to?(:custom_field_definitions)
103
+ readable = record.class.custom_field_definitions.map(&:name).select { |n| policy.custom_field_readable?(n) }
104
+ json["custom_fields"] = json["custom_fields"].to_h.slice(*readable)
105
+ end
106
+
70
107
  # Computed cross-module blocks (OpenLoam::Enrichers), under a separate key so
71
108
  # they're never confused with the record's own columns. An index passes the
72
109
  # batched result (avoiding N+1); a single show computes it here.
@@ -2,13 +2,22 @@
2
2
  # watches it live (L-915). Carries tenant + actor explicitly, like every OpenLoam job.
3
3
  # The per-row summary (created/updated/failed + error rows) is stored on the
4
4
  # ProgressJob's `result` for the summary screen.
5
+ #
6
+ # The file arrives as a blob id, never as a job argument. ActiveJob arguments are
7
+ # serialized into the queue backend and echoed in the job log, so passing the CSV
8
+ # itself would persist every row — including columns bound for encrypted fields —
9
+ # in the clear, outside the encryption the destination columns exist to provide.
5
10
  class ImportJob < ApplicationJob
6
11
  queue_as :default
7
12
 
8
- def perform(entity_type:, csv:, mapping:, match_key:, tenant_id:, actor_id:)
13
+ def perform(entity_type:, blob_id:, mapping:, match_key:, tenant_id:, actor_id:)
9
14
  tenant = OpenLoam::Tenant.find(tenant_id)
10
15
  actor = User.find_by(id: actor_id)
11
16
  model = OpenLoam::Import.allowed_model(entity_type)
17
+ blob = ActiveStorage::Blob.find_by(id: blob_id)
18
+ return if blob.nil? # already purged: nothing to import, not an error
19
+
20
+ csv = blob.download.force_encoding("UTF-8")
12
21
 
13
22
  OpenLoam.as_tenant(tenant, actor: actor) do
14
23
  total = [ CSV.parse(csv).size - 1, 0 ].max
@@ -21,5 +30,9 @@ class ImportJob < ApplicationJob
21
30
  progress.fail!(error.message)
22
31
  end
23
32
  end
33
+ ensure
34
+ # The upload has done its job; leaving it behind is a second copy of the
35
+ # same data with none of the destination's protections.
36
+ blob&.purge_later
24
37
  end
25
38
  end
@@ -8,8 +8,11 @@
8
8
  #
9
9
  # OpenLoam::Encryption.master_key = ENV.fetch("OPEN_LOAM_MASTER_KEY")
10
10
  #
11
- # Rotating the key without re-encrypting orphans existing ciphertext — see
12
- # `bin/rails open_loam:encryption:rotate[Model,tenant_id]`.
11
+ # To ROTATE: keep the outgoing key in OPEN_LOAM_PREVIOUS_MASTER_KEY while the new
12
+ # one is in OPEN_LOAM_MASTER_KEY. Reads fall back to the old key, writes always use
13
+ # the new one, so `bin/rails open_loam:encryption:rotate[Model,tenant_id]` can walk
14
+ # each tenant's rows. Drop the previous key once every model has been rotated —
15
+ # until then, both keys are live and the old one is still worth protecting.
13
16
 
14
17
  # Roles every tenant of this app is expected to have. A registry read by your
15
18
  # own seeding/admin code — OpenLoam does not create memberships for you, because
@@ -65,6 +68,15 @@ OpenLoam.locales = %w[en]
65
68
  # nothing reaches the browser unless it matches a pattern here (security posture).
66
69
  OpenLoam.broadcast_events = [ "open_loam.notification.", "open_loam.progress." ]
67
70
 
71
+ # Events EXCLUDED from the event log (OpenLoam::EventLog), which otherwise
72
+ # captures everything. Progress ticks are excluded because a bulk import fires
73
+ # one per row — volume without history worth keeping.
74
+ OpenLoam.uncaptured_events = [ "open_loam.progress." ]
75
+
76
+ # How long captured events are kept before the daily per-tenant prune. nil keeps
77
+ # everything, which means an unbounded table.
78
+ OpenLoam.event_log_retention = 90.days
79
+
68
80
  # Response enrichers (OpenLoam::Enrichers): attach a computed block onto ANOTHER
69
81
  # module's entity in admin/API responses, with no foreign-key coupling — billing
70
82
  # can annotate an Equipment without Equipment knowing billing exists. Pass a
@@ -3,13 +3,13 @@ class CreateOpenLoamApiTokens < ActiveRecord::Migration[<%= ActiveRecord::VERSIO
3
3
  create_table :open_loam_api_tokens<%= open_loam_id_option %> do |t|
4
4
  t.references :tenant, null: false, foreign_key: { to_table: :open_loam_tenants }<%= open_loam_type_option %>
5
5
  t.references :user, null: false, foreign_key: true<%= open_loam_type_option %>
6
- t.string :token, null: false
6
+ t.string :token_digest, null: false # SHA-256; the plaintext is never stored
7
7
  t.string :label
8
8
  t.datetime :last_used_at
9
9
  t.timestamps
10
10
  end
11
11
  # Tokens are looked up before a tenant is known, so the uniqueness that
12
12
  # matters is global.
13
- add_index :open_loam_api_tokens, :token, unique: true
13
+ add_index :open_loam_api_tokens, :token_digest, unique: true
14
14
  end
15
15
  end
@@ -0,0 +1,13 @@
1
+ class CreateOpenLoamEventRecords < ActiveRecord::Migration[<%= ActiveRecord::VERSION::STRING.to_f %>]
2
+ def change
3
+ create_table :open_loam_event_records<%= open_loam_id_option %> do |t|
4
+ t.references :tenant, null: false, foreign_key: { to_table: :open_loam_tenants }<%= open_loam_type_option %>
5
+ t.string :name, null: false # "rental.equipment.created"
6
+ t.json :payload, null: false # JSON-scalar event payload, as published
7
+ t.datetime :occurred_at, null: false # publish time, not row-write time
8
+ t.timestamps
9
+ end
10
+ # Matches OpenLoam::EventLog.read: tenant, then name or prefix, in time order.
11
+ add_index :open_loam_event_records, %i[tenant_id name occurred_at]
12
+ end
13
+ end
@@ -6,7 +6,6 @@ class CreateOpenLoamInboundWebhooks < ActiveRecord::Migration[<%= ActiveRecord::
6
6
  t.string :token, null: false # unguessable URL id: /webhooks/:token
7
7
  t.string :secret, null: false # HMAC key (authenticates the call)
8
8
  t.string :signature_header, null: false, default: "X-OpenLoam-Signature"
9
- t.string :delivery_id_header # optional: external delivery-id for dedupe
10
9
  t.string :timestamp_header # optional: enables the freshness window
11
10
  t.integer :timestamp_tolerance # seconds; nil = default 300
12
11
  t.string :event_name, null: false # what to publish on the bus
@@ -11,6 +11,9 @@ class CreateOpenLoamSsoProviders < ActiveRecord::Migration[<%= ActiveRecord::VER
11
11
  t.string :jit_role, null: false, default: "employee" # role for JIT-provisioned users
12
12
  t.json :group_role_map, null: false, default: {} # IdP group -> OpenLoam role (first match wins)
13
13
  t.boolean :active, null: false, default: true
14
+ # Proof of domain ownership, stamped by an operator (rake
15
+ # open_loam:sso:verify_domain) — never by the manager who typed the domain.
16
+ t.datetime :domain_verified_at
14
17
  t.timestamps
15
18
  end
16
19
  # HRD resolves a provider by email domain, cross-tenant, before login — so the
@@ -0,0 +1,29 @@
1
+ class CreateOpenLoamWebhookDeliveries < ActiveRecord::Migration[<%= ActiveRecord::VERSION::STRING.to_f %>]
2
+ def change
3
+ create_table :open_loam_webhook_deliveries<%= open_loam_id_option %> do |t|
4
+ t.references :tenant, null: false, foreign_key: { to_table: :open_loam_tenants }<%= open_loam_type_option %>
5
+ t.references :endpoint, null: false, foreign_key: { to_table: :open_loam_webhook_endpoints, on_delete: :cascade }<%= open_loam_type_option %>
6
+ t.string :event_id, null: false # one per published event, shared by its endpoints
7
+ t.string :delivery_id, null: false # one per (event, endpoint), sent as a header
8
+ t.string :event_name, null: false
9
+ t.json :payload, null: false # the event payload (ids and scalars)
10
+ t.string :status, null: false, default: "pending" # pending | sending | succeeded | failed | cancelled
11
+ t.integer :attempts, null: false, default: 0
12
+ t.datetime :next_attempt_at
13
+ t.datetime :sending_at
14
+ t.integer :last_response_code
15
+ t.string :last_error
16
+ t.integer :last_duration_ms
17
+ t.string :response_excerpt, limit: 512
18
+ t.datetime :delivered_at
19
+ t.timestamps
20
+ end
21
+ add_index :open_loam_webhook_deliveries, %i[endpoint_id event_id], unique: true
22
+ add_index :open_loam_webhook_deliveries, :delivery_id, unique: true
23
+ add_index :open_loam_webhook_deliveries, %i[tenant_id status next_attempt_at]
24
+ add_index :open_loam_webhook_deliveries, %i[endpoint_id created_at]
25
+ # The per-minute cross-tenant sweep lookup (overdue / stuck / prunable).
26
+ add_index :open_loam_webhook_deliveries, %i[status next_attempt_at]
27
+ add_index :open_loam_webhook_deliveries, %i[status updated_at]
28
+ end
29
+ end
@@ -3,9 +3,19 @@ class CreateOpenLoamWebhookEndpoints < ActiveRecord::Migration[<%= ActiveRecord:
3
3
  create_table :open_loam_webhook_endpoints<%= open_loam_id_option %> do |t|
4
4
  t.references :tenant, null: false, foreign_key: { to_table: :open_loam_tenants }<%= open_loam_type_option %>
5
5
  t.string :url, null: false
6
- t.string :event_pattern, null: false
7
- t.string :secret, null: false
6
+ t.string :event_pattern # single pattern (0.3.0); nil when event_patterns is used
7
+ t.json :event_patterns, null: false, default: []
8
+ t.text :secret, null: false # plaintext hex, or "v2:..." when encrypt_secrets is on
9
+ t.text :previous_secret
10
+ t.datetime :previous_secret_expires_at
8
11
  t.boolean :active, null: false, default: true
12
+ t.string :description
13
+ t.json :metadata, null: false, default: {} # host-owned settings; OpenLoam never reads it
14
+ t.string :disabled_reason
15
+ t.integer :consecutive_failures, null: false, default: 0
16
+ t.datetime :last_success_at
17
+ t.datetime :last_failure_at
18
+ t.datetime :failing_since # start of the current failure streak
9
19
  t.timestamps
10
20
  end
11
21
  add_index :open_loam_webhook_endpoints, %i[tenant_id active]
@@ -6,7 +6,7 @@ module OpenLoam
6
6
  #
7
7
  # OpenLoam::AuthThrottle.locked?(email) # refuse if true
8
8
  # OpenLoam::AuthThrottle.record_failure(email, kind: "password", ip: request.ip)
9
- # OpenLoam::AuthThrottle.clear(email) # on success
9
+ # OpenLoam::AuthThrottle.clear(email, kind: "password") # on success
10
10
  #
11
11
  # PER-IDENTIFIER is the primary defense (an attacker targets one account /
12
12
  # code). A per-ip throttle to blunt spraying across accounts is a clean
@@ -46,6 +46,9 @@ module OpenLoam
46
46
 
47
47
  # Locked if there are >= max failures within the window. Old attempts age out
48
48
  # of the window automatically (the window query IS the expiry — no reaper).
49
+ #
50
+ # Both auth call sites ask WITHOUT a kind on purpose: failures on either
51
+ # factor lock both, so grinding TOTP also costs the attacker the password form.
49
52
  def locked?(identifier, kind: nil)
50
53
  recent_failures(identifier, kind: kind) >= max_attempts
51
54
  end
@@ -58,8 +61,13 @@ module OpenLoam
58
61
 
59
62
  # Reset the counter — call on a SUCCESSFUL auth so a legitimate user who
60
63
  # eventually gets in isn't left throttled.
61
- def clear(identifier)
62
- attempts(identifier).delete_all
64
+ #
65
+ # Pass `kind:` — clearing every kind on one factor's success lets an attacker
66
+ # holding the password reset the TOTP counter before each guess.
67
+ def clear(identifier, kind: nil)
68
+ scope = attempts(identifier)
69
+ scope = scope.where(kind: Array(kind).map(&:to_s)) if kind
70
+ scope.delete_all
63
71
  end
64
72
 
65
73
  # Seconds until the identifier unlocks (for the "try again in N" message),
@@ -94,7 +94,7 @@ module OpenLoam
94
94
  join = "LEFT JOIN #{table} ON #{table}.indexable_type = #{conn.quote(index_type(model))} " \
95
95
  "AND #{table}.indexable_id = #{model.table_name}.id " \
96
96
  "AND #{table}.field_key = #{conn.quote(field_key.to_s)} " \
97
- "AND #{table}.tenant_id = #{OpenLoam.tenant!.id}"
97
+ "AND #{table}.tenant_id = #{conn.quote(OpenLoam.tenant!.id)}"
98
98
  model.joins(join).order(Arel.sql("#{table}.value_text #{dir.to_s.casecmp('desc').zero? ? 'DESC' : 'ASC'}"))
99
99
  end
100
100
 
@@ -202,16 +202,19 @@ module OpenLoam
202
202
  when "neq" then rows.where.not(value_text: value.to_s)
203
203
  when "contains" then rows.where("value_text LIKE ?", "%#{sanitize_like(value)}%")
204
204
  when "present" then rows.where.not(value_text: [ nil, "" ])
205
- when "gt" then numeric(rows, value, ">")
206
- when "gte" then numeric(rows, value, ">=")
207
- when "lt" then numeric(rows, value, "<")
208
- when "lte" then numeric(rows, value, "<=")
205
+ when "gt", "gte", "lt", "lte" then numeric(rows, value, op)
209
206
  end
210
207
  end
211
208
 
212
- # Numeric comparisons hit the indexed value_number column.
213
- def numeric(rows, value, operator)
214
- rows.where("value_number #{operator} ?", value.to_f)
209
+ # Numeric comparisons hit the indexed value_number column. Built through
210
+ # Arel rather than an interpolated fragment: `op` reaches here from
211
+ # params[:cf_op], and a comparison operator cannot be a bound parameter, so
212
+ # the only safe form is one that never becomes a string.
213
+ NUMERIC_PREDICATES = { "gt" => :gt, "gte" => :gteq, "lt" => :lt, "lte" => :lteq }.freeze
214
+
215
+ def numeric(rows, value, op)
216
+ column = OpenLoam::CustomFieldValue.arel_table[:value_number]
217
+ rows.where(column.public_send(NUMERIC_PREDICATES.fetch(op), value.to_f))
215
218
  end
216
219
 
217
220
  def row_for(record, definition, type)
@@ -88,7 +88,11 @@ module OpenLoam
88
88
  write_attribute(name, OpenLoam::Encryption.encrypt_scoped(value, resolved, aad: aad))
89
89
  # The blind index tracks the ciphertext column: rewrite it in the
90
90
  # same breath, so an exact-match lookup can never go stale.
91
- write_attribute(hash_column, OpenLoam::Encryption.blind_index_scoped(value, resolved)) if searchable
91
+ if searchable
92
+ write_attribute(hash_column,
93
+ OpenLoam::Encryption.blind_index_scoped(value, resolved,
94
+ table: self.class.table_name, column: name))
95
+ end
92
96
  end
93
97
  end
94
98
  end
@@ -98,10 +102,11 @@ module OpenLoam
98
102
  # call must hash-and-compare, never match a plaintext query against the
99
103
  # ciphertext column (which would silently find nothing).
100
104
  def define_open_loam_blind_index_finder(name)
101
- hash_column = "#{name}_hash"
105
+ hash_column = :"#{name}_hash"
102
106
 
103
107
  define_singleton_method("where_#{name}") do |value|
104
- where(hash_column => OpenLoam::Encryption.blind_index(value, OpenLoam.tenant!.id))
108
+ where(hash_column => OpenLoam::Encryption.blind_index(value, OpenLoam.tenant!.id,
109
+ table: table_name, column: name))
105
110
  end
106
111
 
107
112
  define_singleton_method("find_by_#{name}") do |value|
@@ -26,10 +26,26 @@ module OpenLoam
26
26
  KEY_BYTES = 32 # AES-256 and HMAC-SHA256 both take a 32-byte key
27
27
 
28
28
  def data_key(scope:, purpose:)
29
+ derive(scope, purpose, OpenLoam::Encryption.master_key)
30
+ end
31
+
32
+ # The same derivation under the key being rotated away from, so decryption
33
+ # can fall back to it while open_loam:encryption:rotate rewrites rows under
34
+ # the new one. nil when no previous key is configured.
35
+ def previous_data_key(scope:, purpose:)
36
+ previous = OpenLoam::Encryption.previous_master_key
37
+ return nil if previous.nil?
38
+
39
+ derive(scope, purpose, previous)
40
+ end
41
+
42
+ private
43
+
44
+ def derive(scope, purpose, master)
29
45
  raise ArgumentError, "scope is required to derive a key" if scope.nil? || scope.to_s.empty?
30
46
 
31
47
  OpenSSL::KDF.hkdf(
32
- OpenLoam::Encryption.master_key,
48
+ master,
33
49
  salt: SALT,
34
50
  # info binds the key to owner AND purpose. "tenant/5" here reproduces
35
51
  # the pre-scope format exactly, so existing ciphertext still decrypts.