active_record-undo 0.1.5 β 0.2.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.
- checksums.yaml +4 -4
- data/DOCUMENTATION.md +96 -22
- data/README.md +350 -197
- data/app/controllers/active_record/undo/application_controller.rb +91 -0
- data/app/controllers/active_record/undo/logs_controller.rb +87 -0
- data/app/controllers/active_record/undo/restores_controller.rb +11 -0
- data/config/routes.rb +11 -0
- data/lib/active_record/undo/configuration.rb +8 -1
- data/lib/active_record/undo/engine.rb +14 -1
- data/lib/active_record/undo/model_extension/attribution_helper.rb +8 -0
- data/lib/active_record/undo/model_extension/tenant_verification.rb +1 -1
- data/lib/active_record/undo/model_extension.rb +15 -2
- data/lib/active_record/undo/safe_redirect.rb +60 -0
- data/lib/active_record/undo/undo_log.rb +60 -2
- data/lib/active_record/undo/version.rb +1 -1
- data/lib/active_record/undo/view_helpers.rb +101 -0
- data/lib/active_record/undo.rb +13 -0
- metadata +7 -1
data/README.md
CHANGED
|
@@ -3,48 +3,114 @@
|
|
|
3
3
|
[](https://rubygems.org/gems/active_record-undo)
|
|
4
4
|
[](https://opensource.org/licenses/MIT)
|
|
5
5
|
|
|
6
|
-
**ActiveRecord::Undo** brings transactional, cascade-aware soft deletes
|
|
6
|
+
**ActiveRecord::Undo** brings transactional, cascade-aware soft deletes, instant single-line restores, and a mountable HTTP route engine to Ruby on Rails applications.
|
|
7
7
|
|
|
8
|
-
Unlike
|
|
8
|
+
Unlike traditional soft-deletion gems that merely flip a timestamp on a single record, `active_record-undo` creates a polymorphic audit log capturing every affected child record across `dependent: :destroy` and `dependent: :delete_all` associations. Restoring a deleted record cleanly recovers the entire deleted subtree in a single atomic database transactionβwith out-of-the-box support for multi-tenancy, user attribution, background purging, and zero-boilerplate HTTP endpoints.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## Table of Contents
|
|
13
|
+
|
|
14
|
+
- [Features](#features)
|
|
15
|
+
- [Installation \& Migrations](#installation--migrations)
|
|
16
|
+
- [Database Migrations](#database-migrations)
|
|
17
|
+
- [Model Setup](#model-setup)
|
|
18
|
+
- [1. Add Timestamp Column to Tables](#1-add-timestamp-column-to-tables)
|
|
19
|
+
- [2. Declare `acts_as_undoable`](#2-declare-acts_as_undoable)
|
|
20
|
+
- [Basic Usage](#basic-usage)
|
|
21
|
+
- [Cascading Soft Deletes](#cascading-soft-deletes)
|
|
22
|
+
- [Restoring Records](#restoring-records)
|
|
23
|
+
- [Option A: Restore from the model (Recommended)](#option-a-restore-from-the-model-recommended)
|
|
24
|
+
- [Option B: Restore from the `UndoLog`](#option-b-restore-from-the-undolog)
|
|
25
|
+
- [Status \& Eligibility Helpers](#status--eligibility-helpers)
|
|
26
|
+
- [Query Scopes](#query-scopes)
|
|
27
|
+
- [Inspecting Deletion Logs](#inspecting-deletion-logs)
|
|
28
|
+
- [Mountable Route \& Controller Engine](#mountable-route--controller-engine)
|
|
29
|
+
- [Mounting the Engine](#mounting-the-engine)
|
|
30
|
+
- [Available Endpoints](#available-endpoints)
|
|
31
|
+
- [View Helpers (`undo_button_to` \& `undo_link_to`)](#view-helpers-undo_button_to--undo_link_to)
|
|
32
|
+
- [Cryptographic Signed Restore Tokens](#cryptographic-signed-restore-tokens)
|
|
33
|
+
- [Generating \& Using Signed Tokens](#generating--using-signed-tokens)
|
|
34
|
+
- [Key Security Properties](#key-security-properties)
|
|
35
|
+
- [Multi-Format Responses](#multi-format-responses)
|
|
36
|
+
- [Security \& Open-Redirect Protection](#security--open-redirect-protection)
|
|
37
|
+
- [Multi-Tenant Isolation \& User Attribution](#multi-tenant-isolation--user-attribution)
|
|
38
|
+
- [User Attribution (`whodunnit`)](#user-attribution-whodunnit)
|
|
39
|
+
- [Multi-Tenant Scoping](#multi-tenant-scoping)
|
|
40
|
+
- [Tenant Matching Security](#tenant-matching-security)
|
|
41
|
+
- [Configured Context Enforcement](#configured-context-enforcement)
|
|
42
|
+
- [Retention, Expiration \& Purging](#retention-expiration--purging)
|
|
43
|
+
- [Expiration Checks](#expiration-checks)
|
|
44
|
+
- [Purger Service](#purger-service)
|
|
45
|
+
- [ActiveJob Background Worker](#activejob-background-worker)
|
|
46
|
+
- [Rake Task](#rake-task)
|
|
47
|
+
- [Configuration Reference](#configuration-reference)
|
|
48
|
+
- [How It Works](#how-it-works)
|
|
49
|
+
- [Error Reference](#error-reference)
|
|
50
|
+
- [Development](#development)
|
|
51
|
+
- [Contributing](#contributing)
|
|
52
|
+
- [License](#license)
|
|
9
53
|
|
|
10
54
|
---
|
|
11
55
|
|
|
12
56
|
## Features
|
|
13
57
|
|
|
14
|
-
- π **Cascading Soft Deletes:** Soft deletes parent
|
|
15
|
-
- βͺ **Atomic Restores:** Reverses soft deletion for an entire object tree (`
|
|
16
|
-
-
|
|
17
|
-
-
|
|
18
|
-
-
|
|
19
|
-
-
|
|
20
|
-
-
|
|
21
|
-
-
|
|
22
|
-
-
|
|
23
|
-
- π§Ή **
|
|
58
|
+
- π **Cascading Soft Deletes:** Soft deletes parent records along with dependent associations (`dependent: :destroy` / `:delete_all`).
|
|
59
|
+
- βͺ **Atomic Restores:** Reverses soft deletion for an entire object tree (`record.restore!` or `undo_log.restore!`) within a single database transaction.
|
|
60
|
+
- π **Mountable Engine & Endpoints:** Out-of-the-box controller actions for instant undo links with HTML flash redirects, Turbo Streams, and JSON responses.
|
|
61
|
+
- π **Cryptographic Signed Links:** Direct undo restoration tokens (`undo_log.signed_token`) preventing ID enumeration on public or email links.
|
|
62
|
+
- π¨ **Clean View Helpers:** Drop-in `undo_button_to` and `undo_link_to` view helpers for seamless UI integration.
|
|
63
|
+
- π **Restoration Verification (`#undoable?`):** Instantly check if a soft-deleted record is eligible for restore before rendering UI buttons.
|
|
64
|
+
- π€ **User Attribution (`whodunnit`):** Tracks who initiated soft deletes and restores automatically via ambient context or explicit parameters.
|
|
65
|
+
- π’ **Multi-Tenant Isolation:** Scopes deletion logs to specific tenants with strict tenant-matching security.
|
|
66
|
+
- βοΈ **Custom Soft-Delete Columns:** Supports custom columns (e.g., `:archived_at`, `:discarded_at`) per model while defaulting to `:deleted_at`.
|
|
67
|
+
- π§Ή **Retention & Auto-Purging:** Built-in expiration scopes, batch SQL purger, ActiveJob worker, and Rake task with foreign-key constraint protection.
|
|
68
|
+
- π **Zero Generator Setup:** Built as a `Rails::Engine`. Migrations automatically hook into `rails db:migrate`.
|
|
24
69
|
|
|
25
70
|
---
|
|
26
71
|
|
|
27
|
-
## Installation
|
|
72
|
+
## Installation & Migrations
|
|
28
73
|
|
|
29
|
-
Add
|
|
74
|
+
Add the gem to your application's `Gemfile`:
|
|
30
75
|
|
|
31
76
|
```ruby
|
|
32
77
|
gem "active_record-undo"
|
|
33
78
|
```
|
|
34
79
|
|
|
35
|
-
Then
|
|
80
|
+
Then install dependencies:
|
|
36
81
|
|
|
37
82
|
```bash
|
|
38
83
|
bundle install
|
|
39
84
|
```
|
|
40
85
|
|
|
41
|
-
|
|
86
|
+
### Database Migrations
|
|
87
|
+
|
|
88
|
+
`ActiveRecord::Undo` automatically appends its migrations (`undo_logs` and `undo_log_items`) to your application's migration path:
|
|
42
89
|
|
|
43
90
|
```bash
|
|
44
91
|
rails db:migrate
|
|
45
92
|
```
|
|
46
93
|
|
|
47
|
-
*(Optional)* If you
|
|
94
|
+
*(Optional)* If you plan to use **Multi-Tenant Isolation** or **User Attribution**, add the polymorphic columns to `undo_logs`:
|
|
95
|
+
|
|
96
|
+
```ruby
|
|
97
|
+
# db/migrate/XXXXXX_add_tenant_and_whodunnit_to_undo_logs.rb
|
|
98
|
+
class AddTenantAndWhodunnitToUndoLogs < ActiveRecord::Migration[7.0]
|
|
99
|
+
def change
|
|
100
|
+
change_table :undo_logs, bulk: true do |t|
|
|
101
|
+
t.string :whodunnit_type, null: true
|
|
102
|
+
t.bigint :whodunnit_id, null: true
|
|
103
|
+
t.string :tenant_type, null: true
|
|
104
|
+
t.bigint :tenant_id, null: true
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
add_index :undo_logs, [:whodunnit_type, :whodunnit_id], name: "index_undo_logs_on_whodunnit"
|
|
108
|
+
add_index :undo_logs, [:tenant_type, :tenant_id], name: "index_undo_logs_on_tenant"
|
|
109
|
+
end
|
|
110
|
+
end
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
*(Optional)* If you wish to customize the gem's core migration directly:
|
|
48
114
|
|
|
49
115
|
```bash
|
|
50
116
|
rails active_record_undo:install:migrations
|
|
@@ -52,14 +118,14 @@ rails active_record_undo:install:migrations
|
|
|
52
118
|
|
|
53
119
|
---
|
|
54
120
|
|
|
55
|
-
##
|
|
121
|
+
## Model Setup
|
|
56
122
|
|
|
57
|
-
### 1.
|
|
123
|
+
### 1. Add Timestamp Column to Tables
|
|
58
124
|
|
|
59
|
-
Ensure
|
|
125
|
+
Ensure every model using soft deletion has a timestamp column:
|
|
60
126
|
|
|
61
127
|
```ruby
|
|
62
|
-
class
|
|
128
|
+
class AddDeletedAtToModels < ActiveRecord::Migration[7.0]
|
|
63
129
|
def change
|
|
64
130
|
add_column :posts, :deleted_at, :datetime
|
|
65
131
|
add_column :comments, :deleted_at, :datetime
|
|
@@ -72,345 +138,426 @@ class AddSoftDeleteColumnsToModels < ActiveRecord::Migration[7.0]
|
|
|
72
138
|
end
|
|
73
139
|
```
|
|
74
140
|
|
|
75
|
-
### 2.
|
|
141
|
+
### 2. Declare `acts_as_undoable`
|
|
76
142
|
|
|
77
|
-
Add `acts_as_undoable` to models
|
|
143
|
+
Add `acts_as_undoable` to your models. By default, it uses the `:deleted_at` column:
|
|
78
144
|
|
|
79
145
|
```ruby
|
|
80
146
|
class Post < ApplicationRecord
|
|
81
|
-
# Uses default :deleted_at column
|
|
82
147
|
acts_as_undoable
|
|
83
148
|
|
|
84
149
|
has_many :comments, dependent: :destroy
|
|
85
150
|
end
|
|
86
151
|
|
|
87
152
|
class Comment < ApplicationRecord
|
|
88
|
-
# Uses default :deleted_at column
|
|
89
153
|
acts_as_undoable
|
|
90
154
|
|
|
91
155
|
belongs_to :post
|
|
92
156
|
end
|
|
93
157
|
|
|
94
158
|
class ArchiveItem < ApplicationRecord
|
|
95
|
-
# Configured with a custom column
|
|
159
|
+
# Configured with a custom timestamp column
|
|
96
160
|
acts_as_undoable column: :archived_at
|
|
97
161
|
end
|
|
98
162
|
```
|
|
99
163
|
|
|
100
164
|
---
|
|
101
165
|
|
|
102
|
-
##
|
|
166
|
+
## Basic Usage
|
|
103
167
|
|
|
104
|
-
### Soft
|
|
168
|
+
### Cascading Soft Deletes
|
|
105
169
|
|
|
106
|
-
Call `soft_delete!` on
|
|
170
|
+
Call `soft_delete!` on any undoable record. It updates the timestamp column across the record and all dependent associations inside a single database transaction, returning an `ActiveRecord::Undo::UndoLog` instance:
|
|
107
171
|
|
|
108
172
|
```ruby
|
|
109
173
|
post = Post.find(1)
|
|
110
174
|
|
|
111
|
-
# Soft deletes post and all associated comments
|
|
175
|
+
# Soft deletes post and cascades to all associated comments
|
|
112
176
|
undo_log = post.soft_delete!
|
|
113
177
|
|
|
114
|
-
post.soft_deleted?
|
|
178
|
+
post.soft_deleted? # => true
|
|
115
179
|
post.comments.kept.count # => 0
|
|
116
180
|
```
|
|
117
181
|
|
|
118
|
-
###
|
|
182
|
+
### Restoring Records
|
|
119
183
|
|
|
120
|
-
|
|
121
|
-
item = ArchiveItem.find(5)
|
|
122
|
-
item.soft_delete!
|
|
184
|
+
You can restore an entire deleted tree either from the model instance or from the `UndoLog`:
|
|
123
185
|
|
|
124
|
-
|
|
125
|
-
item.archived_at # => 2026-08-08 22:20:16 UTC
|
|
126
|
-
```
|
|
186
|
+
#### Option A: Restore from the model (Recommended)
|
|
127
187
|
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
Use `#undoable?` to verify if a record is soft-deleted and has a corresponding `UndoLog` entry available in the database. This is ideal for conditionally rendering UI elements or validating controller actions:
|
|
188
|
+
Calling `restore!` directly on the model automatically looks up its latest deletion log, executes the atomic restoration, destroys the log records, and reloads the model instance:
|
|
131
189
|
|
|
132
190
|
```ruby
|
|
133
|
-
post
|
|
191
|
+
post.restore!
|
|
134
192
|
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
post.restore!
|
|
138
|
-
end
|
|
193
|
+
post.soft_deleted? # => false
|
|
194
|
+
post.comments.count # => 2
|
|
139
195
|
```
|
|
140
196
|
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
- The record is currently active (not soft deleted).
|
|
144
|
-
- The record was soft deleted manually via direct SQL/column updates without generating an undo log.
|
|
145
|
-
- The corresponding `UndoLog` record was purged or already restored.
|
|
146
|
-
|
|
147
|
-
### Inspect Deletion Logs
|
|
148
|
-
|
|
149
|
-
Inspect affected records through standard Rails associations on the returned `UndoLog`:
|
|
197
|
+
#### Option B: Restore from the `UndoLog`
|
|
150
198
|
|
|
151
199
|
```ruby
|
|
152
|
-
|
|
153
|
-
undo_log.undo_log_items.map(&:item)
|
|
154
|
-
# => [#<Comment 101... id:>, #<Comment 102... id:>, #<Post 1... id:>]
|
|
155
|
-
```
|
|
156
|
-
|
|
157
|
-
### Restoring Records
|
|
200
|
+
undo_log.restore!
|
|
158
201
|
|
|
159
|
-
|
|
202
|
+
post.reload.soft_deleted? # => false
|
|
203
|
+
```
|
|
160
204
|
|
|
161
|
-
|
|
205
|
+
### Status & Eligibility Helpers
|
|
162
206
|
|
|
163
|
-
|
|
207
|
+
`ActiveRecord::Undo` provides fast predicate methods and audit helpers on models:
|
|
164
208
|
|
|
165
209
|
```ruby
|
|
166
|
-
#
|
|
167
|
-
post.
|
|
210
|
+
# Checks if the soft-delete column is set
|
|
211
|
+
post.soft_deleted? # => true / false
|
|
168
212
|
|
|
169
|
-
|
|
170
|
-
post.
|
|
171
|
-
```
|
|
213
|
+
# Verifies record is soft-deleted AND has a valid undo log available in the database
|
|
214
|
+
post.undoable? # => true / false
|
|
172
215
|
|
|
173
|
-
|
|
216
|
+
# Checks if the soft-deleted record has exceeded the configured retention period
|
|
217
|
+
post.expired? # => true / false
|
|
174
218
|
|
|
175
|
-
|
|
176
|
-
#
|
|
177
|
-
|
|
219
|
+
# Retrieves the latest UndoLog audit record associated with this model
|
|
220
|
+
post.undo_log # => #<ActiveRecord::Undo::UndoLog id: 14, ...>
|
|
221
|
+
post.latest_undo_log # alias
|
|
178
222
|
|
|
179
|
-
|
|
180
|
-
post.
|
|
223
|
+
# Generates a cryptographic signed restoration token directly from the model
|
|
224
|
+
post.signed_token # => "eyJfcmFpbHMiOnsiZGF0YSI6..."
|
|
181
225
|
```
|
|
182
226
|
|
|
183
|
-
|
|
227
|
+
> [!TIP]
|
|
228
|
+
> Use `#undoable?` to conditionally display restore buttons in your user interface, passing the model instance directly:
|
|
229
|
+
>
|
|
230
|
+
> ```erb
|
|
231
|
+
> <% if post.undoable? %>
|
|
232
|
+
> <%= undo_button_to(post, text: "Restore") %>
|
|
233
|
+
> <% end %>
|
|
234
|
+
> ```
|
|
184
235
|
|
|
185
|
-
|
|
236
|
+
### Query Scopes
|
|
186
237
|
|
|
187
|
-
|
|
238
|
+
Filter records easily without writing manual SQL:
|
|
188
239
|
|
|
189
240
|
```ruby
|
|
190
|
-
#
|
|
241
|
+
# Only active (non-deleted) records
|
|
191
242
|
Post.kept
|
|
192
243
|
|
|
193
|
-
#
|
|
244
|
+
# Only soft-deleted records
|
|
194
245
|
Post.soft_deleted
|
|
195
246
|
|
|
196
|
-
#
|
|
197
|
-
|
|
247
|
+
# Soft-deleted records past the retention limit
|
|
248
|
+
Post.expired
|
|
249
|
+
|
|
250
|
+
# Retrieve all records including soft-deleted ones
|
|
251
|
+
Post.unscoped.all
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
### Inspecting Deletion Logs
|
|
198
255
|
|
|
199
|
-
|
|
200
|
-
post.undoable?
|
|
256
|
+
Inspect affected records through standard Rails associations on `UndoLog`:
|
|
201
257
|
|
|
202
|
-
|
|
203
|
-
|
|
258
|
+
```ruby
|
|
259
|
+
undo_log.undo_log_items.map(&:item)
|
|
260
|
+
# => [#<Comment id: 101>, #<Comment id: 102>, #<Post id: 1>]
|
|
204
261
|
```
|
|
205
262
|
|
|
206
263
|
---
|
|
207
264
|
|
|
208
|
-
##
|
|
265
|
+
## Mountable Route & Controller Engine
|
|
209
266
|
|
|
210
|
-
|
|
267
|
+
`active_record-undo` provides a mountable Rails engine route and controller endpoints so host applications can handle undo/restore actions via HTTP requests without writing boilerplate controller logic.
|
|
211
268
|
|
|
212
|
-
###
|
|
269
|
+
### Mounting the Engine
|
|
213
270
|
|
|
214
|
-
|
|
271
|
+
Mount the engine in your application routes:
|
|
215
272
|
|
|
216
273
|
```ruby
|
|
217
|
-
# config/
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
config.retention_period = 30.days
|
|
274
|
+
# config/routes.rb
|
|
275
|
+
Rails.application.routes.draw do
|
|
276
|
+
mount ActiveRecord::Undo::Engine => "/undo"
|
|
221
277
|
end
|
|
222
278
|
```
|
|
223
279
|
|
|
224
|
-
|
|
280
|
+
### Available Endpoints
|
|
225
281
|
|
|
226
|
-
|
|
282
|
+
| Method | Route | Controller#Action | Description |
|
|
283
|
+
| :----- | :----------------------- | :----------------------------------- | :----------------------------------------- |
|
|
284
|
+
| `POST` | `/undo/logs/:id/restore` | `active_record/undo/logs#restore` | Restores an `UndoLog` by ID |
|
|
285
|
+
| `POST` | `/undo/restore/:token` | `active_record/undo/restores#create` | Restores an `UndoLog` using a signed token |
|
|
227
286
|
|
|
228
|
-
|
|
287
|
+
### View Helpers (`undo_button_to` & `undo_link_to`)
|
|
229
288
|
|
|
230
|
-
|
|
289
|
+
Clean view helpers are automatically available in all Rails views and forms:
|
|
231
290
|
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
291
|
+
```erb
|
|
292
|
+
<%# Standard button_to targeting /undo/logs/:id/restore %>
|
|
293
|
+
<%= undo_button_to(@undo_log) %>
|
|
235
294
|
|
|
236
|
-
|
|
295
|
+
<%# Pass model instances directly %>
|
|
296
|
+
<%= undo_button_to(post, text: "Undo Delete", class: "btn btn-primary") %>
|
|
237
297
|
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
```
|
|
298
|
+
<%# Secure direct link with signed token (prevents ID enumeration in emails or public links) %>
|
|
299
|
+
<%= undo_button_to(@undo_log, signed: true, class: "btn btn-success") %>
|
|
241
300
|
|
|
242
|
-
|
|
301
|
+
<%# Turbo Stream / Hotwire compatible link %>
|
|
302
|
+
<%= undo_link_to(@undo_log, text: "Undo", class: "text-decoration-underline") %>
|
|
303
|
+
<%= undo_link_to(@undo_log, signed: true) %>
|
|
304
|
+
```
|
|
243
305
|
|
|
244
|
-
|
|
245
|
-
ActiveRecord::Undo::UndoLog.expired # => logs created > 30 days ago
|
|
246
|
-
```
|
|
306
|
+
### Cryptographic Signed Restore Tokens
|
|
247
307
|
|
|
248
|
-
|
|
308
|
+
When exposing restore actions in flash notifications, transactional emails, webhook alerts, or public interfaces, relying on sequential database IDs (e.g., `POST /undo/logs/42/restore`) can expose your application to ID enumeration attacks.
|
|
249
309
|
|
|
250
|
-
|
|
310
|
+
`active_record-undo` provides signed tokens for restoration via tamper-proof, opaque URLs: `POST /undo/restore/:token`.
|
|
251
311
|
|
|
252
|
-
|
|
312
|
+
#### Generating & Using Signed Tokens
|
|
253
313
|
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
314
|
+
**In Views (using helpers):**
|
|
315
|
+
|
|
316
|
+
```erb
|
|
317
|
+
<%# Renders a form POST to /undo/restore/:token %>
|
|
318
|
+
<%= undo_button_to(post, signed: true, text: "Undo Delete", class: "btn btn-outline-primary") %>
|
|
319
|
+
|
|
320
|
+
<%# Renders an anchor tag for Turbo / Hotwire %>
|
|
321
|
+
<%= undo_link_to(post, signed: true, text: "Undo") %>
|
|
257
322
|
```
|
|
258
323
|
|
|
259
|
-
|
|
260
|
-
|
|
324
|
+
**In Controllers, Background Jobs & Mailers:**
|
|
325
|
+
|
|
326
|
+
```ruby
|
|
327
|
+
# Generate token directly from the model instance
|
|
328
|
+
token = post.signed_token
|
|
261
329
|
|
|
262
|
-
|
|
330
|
+
# Or with a custom expiration window
|
|
331
|
+
token = post.signed_token(expires_in: 2.hours)
|
|
263
332
|
|
|
264
|
-
|
|
333
|
+
# Or directly from an UndoLog instance
|
|
334
|
+
token = undo_log.signed_token
|
|
335
|
+
|
|
336
|
+
# Construct full URL for transactional emails or Slack webhooks
|
|
337
|
+
restore_url = active_record_undo.signed_restore_url(token: token)
|
|
338
|
+
```
|
|
339
|
+
|
|
340
|
+
**Manual Verification & Retrieval:**
|
|
265
341
|
|
|
266
342
|
```ruby
|
|
267
|
-
#
|
|
268
|
-
ActiveRecord::Undo::
|
|
343
|
+
# Manually verify and retrieve the associated UndoLog
|
|
344
|
+
undo_log = ActiveRecord::Undo::UndoLog.find_by_signed_token(params[:token])
|
|
269
345
|
```
|
|
270
346
|
|
|
271
|
-
####
|
|
347
|
+
#### Key Security Properties
|
|
272
348
|
|
|
273
|
-
|
|
349
|
+
1. **HMAC-SHA256 Cryptographic Tamper Resistance:** Tokens are signed using `Rails.application.message_verifier(:active_record_undo)` derived securely from your application's `secret_key_base`. Any payload alteration invalidates the cryptographic signature.
|
|
350
|
+
2. **Purpose Isolation (`purpose: :restore`):** Tokens are strictly scoped to restoration. Tokens generated for other purposes (or by other verifiers) are rejected.
|
|
351
|
+
3. **Time-Limited Lifespan:** Tokens include an embedded expiration timestamp (configurable via `config.token_expires_in`, defaults to `24.hours`). Expired tokens are rejected automatically.
|
|
352
|
+
4. **Single-Use Replay Protection:** When `undo_log.restore!` succeeds, it automatically destroys the `UndoLog` and its associated items from the database (`destroy!`). Even if an attacker or user resubmits the signed token before its cryptographic expiration, the database lookup fails and returns `nil`, rendering a `404 Not Found`.
|
|
353
|
+
5. **Multi-Tenant Authorization:** Cryptographic validity only proves the token was authentic. During execution, `undo_log.restore!` still enforces multi-tenant boundary matching against `ActiveRecord::Undo.current_tenant`. An authenticated user from Tenant B cannot use a token from Tenant A to restore data.
|
|
274
354
|
|
|
275
|
-
|
|
276
|
-
# Run with the default batch size of 1000
|
|
277
|
-
$ rails active_record_undo:purge_expired
|
|
355
|
+
### Multi-Format Responses
|
|
278
356
|
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
357
|
+
The engine controller seamlessly handles multiple response formats:
|
|
358
|
+
|
|
359
|
+
- **HTML:** Redirects to `params[:redirect_to]` (if a validated safe URL), `request.referer`, or `config.default_redirect_path` with a flash notice (`flash[:notice] = "Record successfully restored."`).
|
|
360
|
+
- **Turbo Stream (`text/vnd.turbo-stream.html`):** Renders inline `<turbo-stream>` notification elements with HTTP status `200 OK`.
|
|
361
|
+
- **JSON:** Returns `{ "success": true, "restored_items_count": count }` with HTTP status `200 OK`.
|
|
362
|
+
|
|
363
|
+
In error scenarios (missing record, expired action, or security mismatch):
|
|
364
|
+
|
|
365
|
+
- **`403 Forbidden`:** Rendered on `ActiveRecord::Undo::SecurityError` (or HTML redirected with `flash[:alert]`).
|
|
366
|
+
- **`404 Not Found`:** Rendered when the undo log does not exist or has already been restored.
|
|
367
|
+
- **`422 Unprocessable Content`:** Rendered when the undo action has expired beyond the retention period.
|
|
368
|
+
|
|
369
|
+
### Security & Open-Redirect Protection
|
|
370
|
+
|
|
371
|
+
- **CSRF Protection:** Inherits from `ActionController::Base` (or your configured `base_controller`) with CSRF verification enabled.
|
|
372
|
+
- **Open-Redirect Mitigation:** `params[:redirect_to]` and `request.referer` undergo strict URL validation. Only relative paths or URLs matching the request's exact host and port are accepted; foreign or protocol-relative URLs (e.g., `//evil.com`) are rejected in favor of the safe fallback.
|
|
373
|
+
- **Signed Tokens:** `undo_log.signed_token` uses Rails' `message_verifier(:active_record_undo)` to sign tokens cryptographically, preventing tampering, replay, and ID enumeration.
|
|
282
374
|
|
|
283
375
|
---
|
|
284
376
|
|
|
285
377
|
## Multi-Tenant Isolation & User Attribution
|
|
286
378
|
|
|
287
|
-
To support enterprise-grade Rails applications, `active_record-undo`
|
|
379
|
+
To support enterprise-grade Rails applications, `active_record-undo` natively integrates user auditing and tenant scoping.
|
|
288
380
|
|
|
289
|
-
###
|
|
381
|
+
### User Attribution (`whodunnit`)
|
|
290
382
|
|
|
291
|
-
|
|
383
|
+
Track which user initiated a soft deletion or restoration:
|
|
292
384
|
|
|
293
385
|
```ruby
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
t.string :whodunnit_type, null: true
|
|
298
|
-
t.bigint :whodunnit_id, null: true
|
|
299
|
-
t.string :tenant_type, null: true
|
|
300
|
-
t.bigint :tenant_id, null: true
|
|
301
|
-
end
|
|
386
|
+
# 1. Via explicit parameter
|
|
387
|
+
post.soft_delete!(whodunnit: current_user)
|
|
388
|
+
post.restore!(whodunnit: current_user)
|
|
302
389
|
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
390
|
+
# 2. Via Thread / Fiber ambient context
|
|
391
|
+
ActiveRecord::Undo.whodunnit = current_user
|
|
392
|
+
post.soft_delete!
|
|
393
|
+
|
|
394
|
+
# 3. Via global callable proc
|
|
395
|
+
ActiveRecord::Undo.configure do |config|
|
|
396
|
+
config.current_user_method = -> { Current.user }
|
|
306
397
|
end
|
|
307
398
|
```
|
|
308
399
|
|
|
309
|
-
###
|
|
400
|
+
### Multi-Tenant Scoping
|
|
310
401
|
|
|
311
|
-
|
|
402
|
+
Scope soft deletes and logs to accounts or organizations:
|
|
312
403
|
|
|
313
404
|
```ruby
|
|
314
|
-
#
|
|
405
|
+
# 1. Via explicit parameter
|
|
406
|
+
post.soft_delete!(tenant: current_account)
|
|
407
|
+
|
|
408
|
+
# 2. Via Thread / Fiber ambient context
|
|
409
|
+
ActiveRecord::Undo.current_tenant = current_account
|
|
410
|
+
post.soft_delete!
|
|
411
|
+
|
|
412
|
+
# 3. Via global callable proc
|
|
315
413
|
ActiveRecord::Undo.configure do |config|
|
|
316
|
-
# Callable accessors to automatically resolve context
|
|
317
|
-
config.current_user_method = -> { Current.user }
|
|
318
414
|
config.current_tenant_method = -> { Current.account }
|
|
319
415
|
end
|
|
320
416
|
```
|
|
321
417
|
|
|
322
|
-
###
|
|
418
|
+
### Tenant Matching Security
|
|
323
419
|
|
|
324
|
-
|
|
420
|
+
When restoring a log belonging to a tenant, the gem verifies that the executing context's tenant matches the log's tenant. If there is a mismatch or missing tenant context, an `ActiveRecord::Undo::SecurityError` is raised:
|
|
325
421
|
|
|
326
422
|
```ruby
|
|
327
|
-
ActiveRecord::Undo.
|
|
328
|
-
ActiveRecord::Undo
|
|
423
|
+
ActiveRecord::Undo.current_tenant = wrong_account
|
|
424
|
+
post.restore! # => raises ActiveRecord::Undo::SecurityError (Tenant mismatch)
|
|
329
425
|
```
|
|
330
426
|
|
|
331
|
-
|
|
427
|
+
### Configured Context Enforcement
|
|
332
428
|
|
|
333
|
-
|
|
334
|
-
# Capture user and tenant during deletion
|
|
335
|
-
post.soft_delete!(whodunnit: current_user, tenant: current_account)
|
|
429
|
+
When `current_user_method` or `current_tenant_method` is configured via `ActiveRecord::Undo.configure`, operations ensure the context does not evaluate to `nil`:
|
|
336
430
|
|
|
337
|
-
|
|
338
|
-
|
|
431
|
+
```ruby
|
|
432
|
+
# If current_user_method evaluates to nil (e.g., unauthenticated request):
|
|
433
|
+
post.soft_delete! # => raises ActiveRecord::Undo::SecurityError: Configured current_user_method returned nil.
|
|
339
434
|
```
|
|
340
435
|
|
|
341
|
-
|
|
436
|
+
*(If neither method is configured, operations proceed normally without requiring user or tenant context).*
|
|
342
437
|
|
|
343
|
-
|
|
438
|
+
---
|
|
439
|
+
|
|
440
|
+
## Retention, Expiration & Purging
|
|
441
|
+
|
|
442
|
+
To keep your database lean, `active_record-undo` provides retention management and automated background purging.
|
|
443
|
+
|
|
444
|
+
### Expiration Checks
|
|
344
445
|
|
|
345
|
-
|
|
446
|
+
Query and check expired records using the configured retention window (default: `30.days`):
|
|
346
447
|
|
|
347
448
|
```ruby
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
449
|
+
# Scopes
|
|
450
|
+
Post.expired # Soft-deleted posts older than retention period
|
|
451
|
+
ActiveRecord::Undo::UndoLog.expired # Undo logs older than retention period
|
|
351
452
|
|
|
352
|
-
|
|
453
|
+
# Predicates
|
|
454
|
+
post.expired? # => true / false
|
|
455
|
+
undo_log.expired? # => true / false
|
|
456
|
+
```
|
|
353
457
|
|
|
354
|
-
|
|
458
|
+
### Purger Service
|
|
355
459
|
|
|
356
|
-
|
|
357
|
-
- If both user and tenant methods are configured, both must return valid non-nil objects for operations to proceed.
|
|
358
|
-
- If neither method is configured, operations proceed normally without requiring user or tenant context.
|
|
460
|
+
`ActiveRecord::Undo::Purger` performs batch SQL deletes bypassing model callbacks for peak efficiency:
|
|
359
461
|
|
|
360
462
|
```ruby
|
|
361
|
-
#
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
463
|
+
# Purge all expired records and logs across registered models
|
|
464
|
+
ActiveRecord::Undo::Purger.purge_expired!(batch_size: 1000)
|
|
465
|
+
|
|
466
|
+
# Scoped purge for a specific tenant
|
|
467
|
+
ActiveRecord::Undo.current_tenant = account_1
|
|
468
|
+
ActiveRecord::Undo::Purger.purge_expired!
|
|
365
469
|
```
|
|
366
470
|
|
|
367
|
-
|
|
471
|
+
> [!NOTE]
|
|
472
|
+
> **Relational Integrity Protection:** To prevent foreign-key constraint violations (`FOREIGN KEY constraint failed`), `Purger` dynamically resolves dependent associations (`:destroy`, `:delete_all`, `:soft_delete`) and recursively cleans up child records bottom-up before purging parent records. For `:nullify` associations, foreign keys are nullified (or cascaded if restricted by a `NOT NULL` constraint).
|
|
368
473
|
|
|
369
|
-
|
|
474
|
+
### ActiveJob Background Worker
|
|
475
|
+
|
|
476
|
+
Enqueue purges easily via ActiveJob:
|
|
370
477
|
|
|
371
478
|
```ruby
|
|
372
|
-
ActiveRecord::Undo::
|
|
373
|
-
|
|
479
|
+
ActiveRecord::Undo::PurgeJob.perform_later(batch_size: 1000)
|
|
480
|
+
```
|
|
481
|
+
|
|
482
|
+
### Rake Task
|
|
483
|
+
|
|
484
|
+
Run purging from cron, cron-like schedulers, or CI:
|
|
485
|
+
|
|
486
|
+
```bash
|
|
487
|
+
# Default batch size (1000)
|
|
488
|
+
rails active_record_undo:purge_expired
|
|
489
|
+
|
|
490
|
+
# Custom batch size
|
|
491
|
+
BATCH_SIZE=500 rails active_record_undo:purge_expired
|
|
374
492
|
```
|
|
375
493
|
|
|
376
|
-
|
|
494
|
+
---
|
|
495
|
+
|
|
496
|
+
## Configuration Reference
|
|
497
|
+
|
|
498
|
+
Configure all gem options in a single initializer:
|
|
377
499
|
|
|
378
500
|
```ruby
|
|
379
|
-
#
|
|
380
|
-
ActiveRecord::Undo.
|
|
381
|
-
|
|
501
|
+
# config/initializers/active_record_undo.rb
|
|
502
|
+
ActiveRecord::Undo.configure do |config|
|
|
503
|
+
# Default retention period for soft-deleted records and undo logs (defaults to 30.days)
|
|
504
|
+
# Set to nil to disable expiration
|
|
505
|
+
config.retention_period = 30.days
|
|
506
|
+
|
|
507
|
+
# Callable procs to resolve ambient user and tenant context (defaults to nil)
|
|
508
|
+
config.current_user_method = -> { Current.user }
|
|
509
|
+
config.current_tenant_method = -> { Current.account }
|
|
510
|
+
|
|
511
|
+
# Base controller for engine authentication and authorization hooks
|
|
512
|
+
# Defaults to "::ApplicationController" if defined, falling back to ActionController::Base
|
|
513
|
+
config.base_controller = "::ApplicationController"
|
|
514
|
+
|
|
515
|
+
# Fallback redirect path after successful restore when no redirect_to or referer exists
|
|
516
|
+
config.default_redirect_path = ->(main_app) { main_app.root_path }
|
|
517
|
+
|
|
518
|
+
# Expiration duration for signed restore tokens (defaults to 24.hours)
|
|
519
|
+
config.token_expires_in = 24.hours
|
|
520
|
+
|
|
521
|
+
# Custom secret key for signed tokens (defaults to nil, utilizing Rails application verifier)
|
|
522
|
+
config.token_secret_key = nil
|
|
523
|
+
|
|
524
|
+
# Error handling strategy for HTML requests (:auto, :redirect, or :render)
|
|
525
|
+
# Defaults to :auto (redirects with flash alert if referer/redirect_to present, else renders status)
|
|
526
|
+
config.error_handling = :auto
|
|
527
|
+
end
|
|
382
528
|
```
|
|
383
529
|
|
|
384
530
|
---
|
|
385
531
|
|
|
386
532
|
## How It Works
|
|
387
533
|
|
|
388
|
-
1. **Cascade Inspection:**
|
|
389
|
-
2. **
|
|
390
|
-
3. **
|
|
391
|
-
4. **
|
|
392
|
-
5. **
|
|
534
|
+
1. **Cascade Inspection:** On calling `soft_delete!`, `ActiveRecord::Undo::CascadeHandler` reflects on `has_many`, `has_one`, and `belongs_to` associations configured with `dependent: :destroy` or `:delete_all`.
|
|
535
|
+
2. **Column Resolution:** Identifies `record.class.undoable_column` to apply the correct timestamp column (`:deleted_at`, `:archived_at`, etc.) across all affected models.
|
|
536
|
+
3. **Audit Logging:** Creates an `UndoLog` and individual `UndoLogItem` entries storing polymorphic references (`item_type`, `item_id`) for every soft-deleted record.
|
|
537
|
+
4. **Atomic Operation:** Deletions and log creations execute within a single `ActiveRecord::Base.transaction`.
|
|
538
|
+
5. **Reverse Restoration:** Calling `restore!` executes within a transaction, iterating over items in reverse order (`reverse_each`) so parent and dependent records are re-activated in the proper sequence before purging the log.
|
|
393
539
|
|
|
394
540
|
---
|
|
395
541
|
|
|
396
|
-
## Error
|
|
397
|
-
|
|
398
|
-
To ensure database integrity and provide clear debugging context, the gem raises errors in the following scenarios:
|
|
542
|
+
## Error Reference
|
|
399
543
|
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
544
|
+
| Error Class | Trigger Scenario |
|
|
545
|
+
| :---------------------------------- | :---------------------------------------------------------------------------- |
|
|
546
|
+
| `ActiveRecord::Undo::Error` | The configured soft-delete column does not exist on the table. |
|
|
547
|
+
| `ActiveRecord::Undo::Error` | A model class referenced by an `UndoLogItem` was renamed or deleted. |
|
|
548
|
+
| `ActiveRecord::Undo::SecurityError` | Attempted restore where the context's tenant does not match the log's tenant. |
|
|
549
|
+
| `ActiveRecord::Undo::SecurityError` | Attempted restore of a tenant-scoped log when no tenant is set in context. |
|
|
550
|
+
| `ActiveRecord::Undo::SecurityError` | Configured `current_user_method` or `current_tenant_method` returned `nil`. |
|
|
406
551
|
|
|
407
552
|
---
|
|
408
553
|
|
|
409
554
|
## Development
|
|
410
555
|
|
|
411
|
-
|
|
556
|
+
Clone the repository and install dependencies:
|
|
412
557
|
|
|
413
558
|
```bash
|
|
559
|
+
git clone https://github.com/saurabh-activecode/active_record-undo.git
|
|
560
|
+
cd active_record-undo
|
|
414
561
|
bundle install
|
|
415
562
|
```
|
|
416
563
|
|
|
@@ -420,11 +567,17 @@ Run test suite via RSpec:
|
|
|
420
567
|
bundle exec rspec
|
|
421
568
|
```
|
|
422
569
|
|
|
570
|
+
Run RuboCop linting:
|
|
571
|
+
|
|
572
|
+
```bash
|
|
573
|
+
bundle exec rubocop
|
|
574
|
+
```
|
|
575
|
+
|
|
423
576
|
---
|
|
424
577
|
|
|
425
578
|
## Contributing
|
|
426
579
|
|
|
427
|
-
Bug reports and pull requests are welcome on GitHub at
|
|
580
|
+
Bug reports and pull requests are welcome on GitHub at [https://github.com/saurabh-activecode/active_record-undo](https://github.com/saurabh-activecode/active_record-undo).
|
|
428
581
|
|
|
429
582
|
## License
|
|
430
583
|
|