railtracks 0.1.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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 9a69375ccbcb5ced2e7ed191e7c2c1929a2cc9cf257d508c591af1be03a3cf98
4
+ data.tar.gz: cb24036e53e9b13f26d3cf99054c3bea539fc3ee5c6ad606ff62674a5c2dbc5d
5
+ SHA512:
6
+ metadata.gz: 98e794f29c34b82250ca17348336600433f299acf77c155e6cf2c0d7ea3a4933b1beea617ab45c53919ab0a84c28533aadc1e99a82fe3f4ab340db581efdbb3a
7
+ data.tar.gz: f558e05794f292fa57cbcace30193fcb87b8111e7d569b04b85772b030e8c5aa4b5d668a53f8eef3a12d94945a18e0d487045a43e0b4c4a98c4e06dff39add40
data/CHANGELOG.md ADDED
@@ -0,0 +1,41 @@
1
+ # Changelog
2
+
3
+ ## [0.1.0] - 2026-12-04
4
+
5
+ ### Added
6
+
7
+ - Rails engine with an opt-in track configuration. Nothing is enabled by
8
+ default; `Railtracks.configure` validates the retention registry, receipt
9
+ secret, model classes and target model at boot.
10
+ - `Railtracks.retention`, a configured accessor for the retention services
11
+ (`store`, `execution`, `recorded_execution`, `due_for_erasure`).
12
+ - Install generator (`railtracks:install`) and the engine migration for
13
+ `railtracks_erasure_receipts` with adapter-aware check constraints, unique
14
+ indexes and append-only triggers for SQLite and PostgreSQL.
15
+ - Gem-owned `Railtracks::ApplicationRecord`; `Railtracks::ErasureReceipt`
16
+ inherits from it and uses the prefixed table.
17
+ - Gem-owned `ReceiptStore`, `ErasureExecution`, `RecordedErasureExecution` and
18
+ `DueForErasure`. None of them default to a demo model: the target model comes
19
+ from `target_model` or an explicit `model:` argument.
20
+ - Documentation: install, configuration, security model, limits, upgrade and
21
+ migration from the demo application.
22
+ - CI matrix for Rails 7.2, 8.0 and 8.1 with Ruby 3.2, 3.3 and 3.4 on SQLite,
23
+ plus a PostgreSQL leg. Brakeman, bundler-audit and RuboCop jobs remain.
24
+
25
+ ### Changed
26
+
27
+ - The root Rails application is now the dummy/test host for the gem. It keeps
28
+ `User` and `Note`, points at the gem with a path dependency and runs the
29
+ retention tests through the engine.
30
+ - The demo's `AssociationErasureExecution` stays in the host as a concrete
31
+ `User has_notes` adapter.
32
+
33
+ ### Removed
34
+
35
+ - Duplicate retention domain objects from `app/models/railtracks`.
36
+ - The demo's `erasure_receipts` migration in favour of the engine migration and
37
+ the prefixed table.
38
+
39
+ ## [Unreleased]
40
+
41
+ - Planned: tenancy, audit, outbox and contracts tracks.
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mohamed Salahy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,152 @@
1
+ # Railtracks
2
+
3
+ Railtracks is an opt-in framework for Rails applications. It adds **tracks**:
4
+ small, removable guarantees Rails leaves to the application, implemented with
5
+ ActiveRecord, Railties, generators and instrumentation instead of replacing the
6
+ conventions that make Rails productive.
7
+
8
+ The first track is **retention**: declared personal-data actions, a frozen
9
+ erasure plan, transactional execution, append-only HMAC receipts, and a
10
+ fail-closed due-for-erasure query.
11
+
12
+ ## Design rule
13
+
14
+ > A track may add a guarantee. It may not replace ActiveRecord, ActiveJob,
15
+ > routing, caching, or the Rails application structure.
16
+
17
+ Every track must be removable, must fail closed, and must expose its limits.
18
+
19
+ ## Status
20
+
21
+ ```
22
+ railtracks 0.1.0
23
+ core engine and configuration
24
+ retention track
25
+ ```
26
+
27
+ The gem is ready for a 0.1.0 release candidate. The repository's root Rails
28
+ application is the dummy/test host; it exercises the engine through a path
29
+ dependency.
30
+
31
+ ## Requirements
32
+
33
+ | Component | Supported |
34
+ | --- | --- |
35
+ | Ruby | 3.2, 3.3, 3.4 |
36
+ | Rails | 7.2, 8.0, 8.1 |
37
+ | Databases | SQLite (development/test), PostgreSQL (production evidence store) |
38
+
39
+ ## Installation
40
+
41
+ ```ruby
42
+ # Gemfile
43
+ gem "railtracks"
44
+ ```
45
+
46
+ ```sh
47
+ bundle install
48
+ bin/rails generate railtracks:install
49
+ bin/rails railtracks:install:migrations
50
+ bin/rails db:migrate
51
+ ```
52
+
53
+ The install generator writes `config/initializers/railtracks.rb`. The migration
54
+ copies the engine migration into the host. Nothing is enabled until the
55
+ retention track is configured.
56
+
57
+ **Keep a SQL structure dump.** The append-only triggers and check constraints
58
+ cannot be represented in `schema.rb`:
59
+
60
+ ```ruby
61
+ # config/application.rb
62
+ config.active_record.schema_format = :sql
63
+ ```
64
+
65
+ See [docs/install.md](docs/install.md) for the full guide.
66
+
67
+ ## Configuration
68
+
69
+ ```ruby
70
+ # config/initializers/railtracks.rb
71
+ Rails.application.config.to_prepare do
72
+ Railtracks.configure do |config|
73
+ config.track :retention do |retention|
74
+ retention.receipt_secret = Rails.application.credentials.railtracks_secret
75
+ retention.registry = Railtracks::Registry.from_yaml(
76
+ Rails.root.join("config/railtracks.yml")
77
+ )
78
+ retention.model_classes = [ User, Note ]
79
+ retention.target_model = User
80
+ end
81
+ end
82
+ end
83
+ ```
84
+
85
+ `Railtracks.configure` validates the registry, the receipt secret and the model
86
+ classes during boot. An invalid configuration fails at boot rather than at the
87
+ first erasure request.
88
+
89
+ ## Usage
90
+
91
+ ```ruby
92
+ receipt = Railtracks.retention.recorded_execution.call(
93
+ "subject-123",
94
+ idempotency_key: "request-2026-12-02-0001"
95
+ )
96
+
97
+ receipt.verified?(Railtracks.retention.receipt_secret) # => true
98
+ ```
99
+
100
+ Planning, auditing and due reports are separate, non-writing services:
101
+
102
+ ```ruby
103
+ registry = Railtracks.retention.registry
104
+ registry.plan(subject: "subject-123", as_of: Time.now.utc)
105
+
106
+ Railtracks::SchemaAudit.new(registry, [ User, Note ]).findings
107
+ Railtracks.retention.due_for_erasure.call(limit: 100)
108
+ ```
109
+
110
+ There is no default model. Supply `target_model` in configuration or pass
111
+ `model:` explicitly:
112
+
113
+ ```ruby
114
+ Railtracks.retention.execution(model: "Account").call("subject-123")
115
+ ```
116
+
117
+ ## Tracks
118
+
119
+ | Track | Guarantee | Status |
120
+ | --- | --- | --- |
121
+ | `retention` | Declared data actions, frozen plans, append-only erasure receipts, due reports | 0.1.0 |
122
+ | `tenancy` | Fail-closed tenant boundaries | Planned |
123
+ | `audit` | Append-only evidence for changes | Planned |
124
+ | `outbox` | Transactional writes and idempotent jobs | Planned |
125
+ | `contracts` | Request and response contracts at the edge | Planned |
126
+
127
+ ## Documentation
128
+
129
+ - [Install](docs/install.md)
130
+ - [Configuration](docs/configuration.md)
131
+ - [Security model](docs/security-model.md)
132
+ - [Limits](docs/limits.md)
133
+ - [Upgrade](docs/upgrade.md)
134
+ - [Migrating from the demo application](docs/migration-from-demo.md)
135
+
136
+ ## Development
137
+
138
+ ```sh
139
+ bundle install
140
+ bundle exec rake test
141
+ bundle exec rubocop
142
+ ```
143
+
144
+ The dummy application is the Rails app at the repository root. The gem lives in
145
+ `railtracks/`.
146
+
147
+ CI runs the test suite on Rails 7.2, 8.0 and 8.1 with Ruby 3.2, 3.3 and 3.4 on
148
+ SQLite, plus a PostgreSQL leg for Rails 8.1 and Ruby 3.4.
149
+
150
+ ## Licence
151
+
152
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Railtracks
4
+ # Abstract base class for every model the engine owns.
5
+ #
6
+ # It deliberately does not inherit from the host application's
7
+ # ApplicationRecord: the host may define its own conventions, callbacks or
8
+ # table-name prefix, and gem-owned tables must not inherit them. The engine
9
+ # models set their prefixed table names explicitly so the host's
10
+ # `table_name_prefix` cannot move evidence to another table.
11
+ class ApplicationRecord < ActiveRecord::Base
12
+ self.abstract_class = true
13
+ end
14
+ end
@@ -0,0 +1,162 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Railtracks
4
+ # Answers "which subjects are due for erasure now?" from stored evidence.
5
+ #
6
+ # This is a bounded administrative query, not a deletion workflow. It reports
7
+ # the receipts whose longest declared retention has elapsed as of a supplied
8
+ # UTC instant, and it refuses to hide evidence it cannot account for.
9
+ #
10
+ # Every stored receipt lands in exactly one of three buckets in the returned
11
+ # Report:
12
+ #
13
+ # * `entries` — the receipt verifies against the secret and its model has a
14
+ # declaration, so a due date can be computed. Only these are "due" answers.
15
+ # * `unverifiable` — the stored row does not match its own HMAC and
16
+ # fingerprint. A row edited by someone who bypassed the append-only
17
+ # triggers, or a query run with the wrong secret, fails verification here
18
+ # instead of being reported as ordinary due evidence.
19
+ # * `undatable` — the receipt is intact but its model no longer has a
20
+ # declaration, so the current declaration set cannot say when it is due.
21
+ #
22
+ # Earlier versions dropped the last two categories with `next unless
23
+ # retention`. That made undeclared or tampered evidence invisible, so an
24
+ # operator saw "nothing due" when the honest answer was "I cannot tell".
25
+ # `Report#complete?` is the fail-closed signal: it is false whenever any
26
+ # evidence could not be verified or dated.
27
+ #
28
+ # The retention period is attached to the registry declaration, not to the
29
+ # receipt, so a due date is always computed from the current declaration set.
30
+ # A changed declaration therefore changes the answer; the receipt keeps the
31
+ # fingerprint of the plan that actually ran so the two can be compared, but
32
+ # this query does not itself decide whether a fingerprint drift is acceptable.
33
+ #
34
+ # There is intentionally no controller or route for this query. Callers are
35
+ # trusted internal code, and the limit is clamped to a bounded range.
36
+ class DueForErasure
37
+ DEFAULT_LIMIT = 100
38
+ MAX_LIMIT = 1_000
39
+
40
+ class Error < StandardError; end
41
+ class ConfigurationError < Error; end
42
+
43
+ Entry = Data.define(:subject_token, :model, :schema_fingerprint, :completed_at, :due_at, :retention)
44
+ Undatable = Data.define(:subject_token, :model, :schema_fingerprint, :completed_at, :reason)
45
+ Unverifiable = Data.define(:subject_token, :model, :schema_fingerprint, :completed_at, :reason)
46
+
47
+ # `complete?` is false when any evidence was skipped, so a caller that only
48
+ # wants a clean answer can require it and treat the query as inconclusive.
49
+ Report = Data.define(:entries, :undatable, :unverifiable, :as_of, :limit, :truncated) do
50
+ def complete?
51
+ undatable.empty? && unverifiable.empty? && !truncated
52
+ end
53
+
54
+ def due_count
55
+ entries.length
56
+ end
57
+ end
58
+
59
+ def initialize(registry:, secret:, now: Time.now.utc)
60
+ raise ConfigurationError, "A receipt secret is required" if secret.to_s.strip.empty?
61
+
62
+ @registry = registry
63
+ @secret = secret
64
+ @now = now
65
+ end
66
+
67
+ # Returns a Report. `limit` is clamped rather than raising, so a bad caller
68
+ # cannot request an unbounded scan, and it bounds every bucket so a single
69
+ # large category cannot dominate memory.
70
+ def call(limit: DEFAULT_LIMIT, subject_token: nil)
71
+ requested = bounded(limit)
72
+ entries = []
73
+ undatable = []
74
+ unverifiable = []
75
+
76
+ scope = ErasureReceipt.order(:completed_at, :id)
77
+ scope = scope.where(subject_token: subject_token) if subject_token
78
+ scope.find_each do |receipt|
79
+ unless receipt.verified?(@secret)
80
+ unverifiable << unverifiable_record(receipt)
81
+ next
82
+ end
83
+
84
+ retention = retention_for(receipt)
85
+ if retention.nil?
86
+ undatable << undatable_record(receipt)
87
+ next
88
+ end
89
+
90
+ due_at = receipt.completed_at + retention.seconds
91
+ next if due_at > @now
92
+
93
+ entries << Entry.new(
94
+ subject_token: receipt.subject_token,
95
+ model: receipt.model,
96
+ schema_fingerprint: receipt.schema_fingerprint,
97
+ completed_at: receipt.completed_at,
98
+ due_at: due_at,
99
+ retention: retention.text
100
+ )
101
+ end
102
+
103
+ entries.sort_by! { |entry| [ entry.due_at, entry.subject_token, entry.model ] }
104
+
105
+ Report.new(
106
+ entries: entries.first(requested).freeze,
107
+ undatable: undatable.first(requested).freeze,
108
+ unverifiable: unverifiable.first(requested).freeze,
109
+ as_of: @now,
110
+ limit: requested,
111
+ truncated: entries.length > requested || undatable.length > requested || unverifiable.length > requested
112
+ )
113
+ end
114
+
115
+ # A single receipt is due only when it verifies and its model is declared,
116
+ # so an inconclusive row never reads as a clean "not yet due" answer.
117
+ def due?(receipt)
118
+ return false unless receipt.verified?(@secret)
119
+
120
+ retention = retention_for(receipt)
121
+ return false if retention.nil?
122
+
123
+ receipt.completed_at + retention.seconds <= @now
124
+ end
125
+
126
+ private
127
+
128
+ def bounded(limit)
129
+ requested = Integer(limit, exception: false) || DEFAULT_LIMIT
130
+ requested.clamp(1, MAX_LIMIT)
131
+ end
132
+
133
+ def unverifiable_record(receipt)
134
+ Unverifiable.new(
135
+ subject_token: receipt.subject_token,
136
+ model: receipt.model,
137
+ schema_fingerprint: receipt.schema_fingerprint,
138
+ completed_at: receipt.completed_at,
139
+ reason: "Receipt does not verify against the configured secret"
140
+ )
141
+ end
142
+
143
+ def undatable_record(receipt)
144
+ Undatable.new(
145
+ subject_token: receipt.subject_token,
146
+ model: receipt.model,
147
+ schema_fingerprint: receipt.schema_fingerprint,
148
+ completed_at: receipt.completed_at,
149
+ reason: "No declaration exists for #{receipt.model}, so no retention applies"
150
+ )
151
+ end
152
+
153
+ def retention_for(receipt)
154
+ declarations = @registry.actions_for(receipt.model)
155
+ return nil if declarations.empty?
156
+
157
+ # The receipt is evidence for the whole plan. The plan becomes due when
158
+ # every declaration in it is due, i.e. when the longest retention ends.
159
+ declarations.map { |d| RetentionPeriod.parse(d.retention) }.max_by(&:seconds)
160
+ end
161
+ end
162
+ end
@@ -0,0 +1,106 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "openssl"
4
+ require "time"
5
+
6
+ module Railtracks
7
+ # Applies a declared erasure plan to one subject in a single transaction.
8
+ #
9
+ # There is no default target model. The model is either supplied when the
10
+ # service is built (normally from `Railtracks.retention.target_model`) or
11
+ # passed explicitly to `#call`. A missing target fails closed before any
12
+ # write.
13
+ class ErasureExecution
14
+ class Error < StandardError; end
15
+ class SubjectNotFound < Error; end
16
+ class SchemaMismatch < Error; end
17
+ class ConfigurationError < Error; end
18
+
19
+ attr_reader :model
20
+
21
+ def initialize(registry:, model_classes:, secret:, model: nil)
22
+ raise ConfigurationError, "An erasure receipt secret is required" if secret.to_s.strip.empty?
23
+ @registry = registry
24
+ @model_classes = model_classes
25
+ @secret = secret
26
+ @model = normalize_model(model)
27
+ end
28
+
29
+ # Fail closed before any write: the target model must be known and every
30
+ # column of the audited models must have a declaration.
31
+ def validate!(model: @model, audit_models: nil)
32
+ model = normalize_model(model)
33
+ raise ConfigurationError, "A target model is required" if model.nil?
34
+
35
+ model_class = @model_classes.find { |klass| klass.name == model }
36
+ raise SchemaMismatch, "#{model} model is not loaded" unless model_class
37
+ audit = SchemaAudit.new(@registry, audit_models || [ model_class ])
38
+ findings = audit.findings.select { |finding| finding.model == model }
39
+ raise SchemaMismatch, findings.map(&:message).join("; ") if findings.any?
40
+
41
+ model_class
42
+ end
43
+
44
+ # Applies the declared plan in one transaction and returns a frozen receipt.
45
+ def call(subject_ref, model: @model, audit_models: nil)
46
+ raise SubjectNotFound, "Subject reference is required" if subject_ref.blank?
47
+ model = normalize_model(model)
48
+ model_class = validate!(model: model, audit_models: audit_models)
49
+ fingerprint = schema_fingerprint
50
+ completed_at = Time.now.utc
51
+
52
+ receipt = nil
53
+ model_class.transaction do
54
+ record = model_class.find_by!(subject_ref: subject_ref)
55
+ receipt = {
56
+ subject: subject_token(subject_ref),
57
+ model: model,
58
+ actions: apply_plan(record, subject_ref, model),
59
+ completed_at: completed_at,
60
+ schema_fingerprint: fingerprint
61
+ }
62
+ end
63
+ receipt[:actions].each(&:freeze)
64
+ receipt.freeze
65
+ end
66
+
67
+ def subject_token(subject_ref)
68
+ SubjectToken.derive(secret: @secret, subject_ref: subject_ref)
69
+ end
70
+
71
+ def schema_fingerprint
72
+ SchemaFingerprint.new(registry: @registry, model_classes: @model_classes).to_s
73
+ end
74
+
75
+ private
76
+
77
+ def normalize_model(model)
78
+ return nil if model.nil?
79
+
80
+ model.respond_to?(:name) ? model.name : model.to_s
81
+ end
82
+
83
+ def apply_plan(record, subject_ref, model)
84
+ @registry.actions_for(model).map do |declaration|
85
+ case declaration.action
86
+ when :delete
87
+ # Write only the declared column. update! would move updated_at even
88
+ # when the plan says to retain it, so the receipt would claim a retain
89
+ # that did not happen.
90
+ record.update_columns(declaration.column => nil)
91
+ { column: declaration.column, action: :deleted }
92
+ when :pseudonymize
93
+ value = declaration.column == "subject_ref" ? subject_token(subject_ref) : pseudonym(record, declaration.column)
94
+ record.update_columns(declaration.column => value)
95
+ { column: declaration.column, action: :pseudonymized }
96
+ when :retain
97
+ { column: declaration.column, action: :retained }
98
+ end
99
+ end
100
+ end
101
+
102
+ def pseudonym(record, column)
103
+ "erased-#{OpenSSL::HMAC.hexdigest("SHA256", @secret, "#{record.class.name.underscore}:#{record.id}:#{column}")}"
104
+ end
105
+ end
106
+ end
@@ -0,0 +1,112 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+ require "json"
5
+ require "openssl"
6
+ require "time"
7
+
8
+ module Railtracks
9
+ # Durable, append-only evidence that a declared erasure plan completed.
10
+ #
11
+ # A receipt stores only the pseudonymous subject token, the canonical model
12
+ # name, the plan's schema fingerprint, the action outcomes, and two digests
13
+ # over that content. It never stores the original subject reference. The row
14
+ # is written once: the model refuses persisted mutations, unique indexes reject
15
+ # duplicates, and the engine migration installs triggers that reject UPDATE
16
+ # and DELETE on both SQLite and PostgreSQL.
17
+ #
18
+ # This is a technical integrity control, not a legal certificate.
19
+ class ErasureReceipt < ApplicationRecord
20
+ self.table_name = "railtracks_erasure_receipts"
21
+
22
+ DOMAIN = "railtracks.erasure-receipt.v1"
23
+ HEX64 = /\A[0-9a-f]{64}\z/
24
+ MODEL_NAME = /\A[A-Z][A-Za-z0-9_:]*\z/
25
+ IDEMPOTENCY_KEY = /\A[A-Za-z0-9][A-Za-z0-9._:-]{7,127}\z/
26
+
27
+ scope :for_subject, ->(subject_token) { where(subject_token: subject_token).order(completed_at: :asc, id: :asc) }
28
+ scope :recent_first, -> { order(completed_at: :desc, id: :desc) }
29
+
30
+ validates :subject_token, presence: true, format: { with: SubjectToken::FORMAT }
31
+ validates :model, presence: true, format: { with: MODEL_NAME }
32
+ validates :schema_fingerprint, presence: true, format: { with: HEX64 }
33
+ validates :idempotency_key, presence: true, format: { with: IDEMPOTENCY_KEY }
34
+ validates :fingerprint, presence: true, format: { with: HEX64 }
35
+ validates :signature, presence: true, format: { with: HEX64 }
36
+ validates :completed_at, presence: true
37
+ validate :actions_are_an_array
38
+
39
+ class << self
40
+ # PostgreSQL stores timestamps at microsecond precision. Truncating here
41
+ # (rather than relying on the adapter) keeps the canonical payload and the
42
+ # stored value identical, so a round-trip receipt still verifies.
43
+ def canonical_payload(subject_token:, model:, schema_fingerprint:, actions:, completed_at:)
44
+ normalized_actions = Array(actions).map do |action|
45
+ {
46
+ "column" => (action[:column] || action["column"]).to_s,
47
+ "action" => (action[:action] || action["action"]).to_s
48
+ }
49
+ end
50
+ normalized_actions.sort_by! { |action| [ action["column"], action["action"] ] }
51
+
52
+ {
53
+ "domain" => DOMAIN,
54
+ "subject_token" => subject_token.to_s,
55
+ "model" => model.to_s,
56
+ "schema_fingerprint" => schema_fingerprint.to_s,
57
+ "actions" => normalized_actions,
58
+ "completed_at" => completed_at.utc.floor(6).iso8601(6)
59
+ }
60
+ end
61
+
62
+ def fingerprint_for(payload)
63
+ Digest::SHA256.hexdigest(JSON.generate(payload))
64
+ end
65
+
66
+ def signature_for(payload, secret)
67
+ OpenSSL::HMAC.hexdigest("SHA256", secret, JSON.generate(payload))
68
+ end
69
+
70
+ # Default idempotency key for a plan: stable for the same subject token,
71
+ # model, and schema fingerprint, so a retried request is recognized even
72
+ # if no explicit request key was supplied.
73
+ def plan_idempotency_key(subject_token:, model:, schema_fingerprint:)
74
+ Digest::SHA256.hexdigest(JSON.generate([ DOMAIN, "plan", subject_token.to_s, model.to_s, schema_fingerprint.to_s ]))
75
+ end
76
+ end
77
+
78
+ # Never let a loaded row be updated or destroyed through Active Record.
79
+ def readonly?
80
+ persisted?
81
+ end
82
+
83
+ def canonical_payload
84
+ self.class.canonical_payload(
85
+ subject_token: subject_token,
86
+ model: model,
87
+ schema_fingerprint: schema_fingerprint,
88
+ actions: actions,
89
+ completed_at: completed_at
90
+ )
91
+ end
92
+
93
+ # Recompute both digests from the stored row. A row edited by someone who
94
+ # can bypass the triggers fails this check even though the row still exists.
95
+ def verified?(secret)
96
+ raise ArgumentError, "A receipt secret is required" if secret.to_s.empty?
97
+
98
+ expected_fingerprint = self.class.fingerprint_for(canonical_payload)
99
+ expected_signature = self.class.signature_for(canonical_payload, secret)
100
+ ActiveSupport::SecurityUtils.secure_compare(fingerprint, expected_fingerprint) &
101
+ ActiveSupport::SecurityUtils.secure_compare(signature, expected_signature)
102
+ end
103
+
104
+ private
105
+
106
+ def actions_are_an_array
107
+ return if actions.is_a?(Array) && actions.all? { |a| a.is_a?(Hash) && a["column"].is_a?(String) && a["action"].is_a?(String) }
108
+
109
+ errors.add(:actions, "must be an array of column/action pairs")
110
+ end
111
+ end
112
+ end