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 +7 -0
- data/CHANGELOG.md +41 -0
- data/LICENSE +21 -0
- data/README.md +152 -0
- data/app/models/railtracks/application_record.rb +14 -0
- data/app/models/railtracks/due_for_erasure.rb +162 -0
- data/app/models/railtracks/erasure_execution.rb +106 -0
- data/app/models/railtracks/erasure_receipt.rb +112 -0
- data/app/models/railtracks/receipt_store.rb +140 -0
- data/app/models/railtracks/recorded_erasure_execution.rb +61 -0
- data/db/migrate/20261204000000_create_railtracks_erasure_receipts.rb +177 -0
- data/docs/configuration.md +132 -0
- data/docs/install.md +90 -0
- data/docs/limits.md +91 -0
- data/docs/migration-from-demo.md +136 -0
- data/docs/security-model.md +100 -0
- data/docs/upgrade.md +69 -0
- data/lib/generators/railtracks/install/install_generator.rb +18 -0
- data/lib/generators/railtracks/install/templates/initializer.rb +18 -0
- data/lib/railtracks/configuration.rb +101 -0
- data/lib/railtracks/engine.rb +17 -0
- data/lib/railtracks/registry.rb +72 -0
- data/lib/railtracks/retention.rb +74 -0
- data/lib/railtracks/retention_period.rb +39 -0
- data/lib/railtracks/schema_audit.rb +43 -0
- data/lib/railtracks/schema_fingerprint.rb +30 -0
- data/lib/railtracks/subject_token.rb +26 -0
- data/lib/railtracks/version.rb +5 -0
- data/lib/railtracks.rb +43 -0
- metadata +102 -0
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "time"
|
|
4
|
+
|
|
5
|
+
module Railtracks
|
|
6
|
+
# Writes erasure receipts exactly once per erasure event.
|
|
7
|
+
#
|
|
8
|
+
# Two independent durable guards make duplicate handling safe:
|
|
9
|
+
#
|
|
10
|
+
# * the plan key (subject token, model name, schema fingerprint) is unique, so
|
|
11
|
+
# a repeated erasure request cannot add a second receipt for the same plan;
|
|
12
|
+
# * the idempotency key is unique, so a retried request key cannot add a
|
|
13
|
+
# second receipt even when the plan changed between attempts.
|
|
14
|
+
#
|
|
15
|
+
# Every write is an INSERT ... ON CONFLICT DO NOTHING, and a conflict returns
|
|
16
|
+
# the stored row instead of overwriting evidence. If the stored row disagrees
|
|
17
|
+
# with the request, the store raises PlanConflict. The store never sees or
|
|
18
|
+
# stores the original subject reference. It is an internal service object with
|
|
19
|
+
# no HTTP endpoint; there is deliberately no route that can erase, read, or
|
|
20
|
+
# delete receipts.
|
|
21
|
+
class ReceiptStore
|
|
22
|
+
class Error < StandardError; end
|
|
23
|
+
class ConfigurationError < Error; end
|
|
24
|
+
class InvalidReceipt < Error; end
|
|
25
|
+
class PlanConflict < Error; end
|
|
26
|
+
|
|
27
|
+
# These names are part of the engine migration. Keep them in sync when the
|
|
28
|
+
# table or index names change.
|
|
29
|
+
TABLE_NAME = "railtracks_erasure_receipts"
|
|
30
|
+
PLAN_KEY_INDEX = "index_railtracks_erasure_receipts_on_plan_key"
|
|
31
|
+
IDEMPOTENCY_INDEX = "index_railtracks_erasure_receipts_on_idempotency_key"
|
|
32
|
+
ACTIONS = %w[deleted pseudonymized retained].freeze
|
|
33
|
+
|
|
34
|
+
def initialize(secret:)
|
|
35
|
+
raise ConfigurationError, "A receipt secret is required" if secret.to_s.strip.empty?
|
|
36
|
+
@secret = secret
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
# `idempotency_key` defaults to a digest of the plan itself. Callers that
|
|
40
|
+
# retry a request may pass their own stable request key instead; the plan
|
|
41
|
+
# key still prevents a second receipt for the same plan.
|
|
42
|
+
def record(subject_token:, model:, schema_fingerprint:, actions:, completed_at:, idempotency_key: nil)
|
|
43
|
+
idempotency_key ||= ErasureReceipt.plan_idempotency_key(
|
|
44
|
+
subject_token: subject_token,
|
|
45
|
+
model: model,
|
|
46
|
+
schema_fingerprint: schema_fingerprint
|
|
47
|
+
)
|
|
48
|
+
# Truncate before both hashing and storing so the canonical payload and
|
|
49
|
+
# the PostgreSQL microsecond value never diverge.
|
|
50
|
+
completed_at = completed_at.utc.floor(6)
|
|
51
|
+
payload = ErasureReceipt.canonical_payload(
|
|
52
|
+
subject_token: subject_token,
|
|
53
|
+
model: model,
|
|
54
|
+
schema_fingerprint: schema_fingerprint,
|
|
55
|
+
actions: actions,
|
|
56
|
+
completed_at: completed_at
|
|
57
|
+
)
|
|
58
|
+
validate_payload!(payload, idempotency_key)
|
|
59
|
+
|
|
60
|
+
attributes = {
|
|
61
|
+
subject_token: payload["subject_token"],
|
|
62
|
+
model: payload["model"],
|
|
63
|
+
schema_fingerprint: payload["schema_fingerprint"],
|
|
64
|
+
idempotency_key: idempotency_key,
|
|
65
|
+
actions: payload["actions"],
|
|
66
|
+
completed_at: completed_at,
|
|
67
|
+
fingerprint: ErasureReceipt.fingerprint_for(payload),
|
|
68
|
+
signature: ErasureReceipt.signature_for(payload, @secret),
|
|
69
|
+
created_at: Time.current,
|
|
70
|
+
updated_at: Time.current
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
receipt = insert_or_find_by_plan(attributes)
|
|
74
|
+
ensure_same_evidence!(receipt, payload)
|
|
75
|
+
receipt
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
def find(subject_token:, model:, schema_fingerprint:)
|
|
79
|
+
ErasureReceipt.find_by(
|
|
80
|
+
subject_token: subject_token,
|
|
81
|
+
model: model,
|
|
82
|
+
schema_fingerprint: schema_fingerprint
|
|
83
|
+
)
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
def find_by_idempotency_key(idempotency_key)
|
|
87
|
+
ErasureReceipt.find_by(idempotency_key: idempotency_key)
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
def receipts_for(subject_token)
|
|
91
|
+
ErasureReceipt.for_subject(subject_token).to_a
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
private
|
|
95
|
+
|
|
96
|
+
def insert_or_find_by_plan(attributes)
|
|
97
|
+
inserted = ErasureReceipt.insert_all([ attributes ], returning: %w[id], unique_by: PLAN_KEY_INDEX)
|
|
98
|
+
return ErasureReceipt.find(inserted.first.fetch("id")) if inserted.any?
|
|
99
|
+
|
|
100
|
+
ErasureReceipt.find_by!(
|
|
101
|
+
subject_token: attributes[:subject_token],
|
|
102
|
+
model: attributes[:model],
|
|
103
|
+
schema_fingerprint: attributes[:schema_fingerprint]
|
|
104
|
+
)
|
|
105
|
+
rescue ActiveRecord::RecordNotUnique
|
|
106
|
+
# The idempotency key collided with a row for a different plan. Re-read it
|
|
107
|
+
# so the caller gets a PlanConflict instead of a raw driver error.
|
|
108
|
+
ErasureReceipt.find_by!(idempotency_key: attributes[:idempotency_key])
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
def ensure_same_evidence!(receipt, payload)
|
|
112
|
+
same = receipt.actions == payload["actions"] &&
|
|
113
|
+
receipt.subject_token == payload["subject_token"] &&
|
|
114
|
+
receipt.model == payload["model"] &&
|
|
115
|
+
receipt.schema_fingerprint == payload["schema_fingerprint"]
|
|
116
|
+
raise PlanConflict, "Existing receipt disagrees with the retried erasure plan" unless same
|
|
117
|
+
end
|
|
118
|
+
|
|
119
|
+
def validate_payload!(payload, idempotency_key)
|
|
120
|
+
unless SubjectToken.valid?(payload["subject_token"])
|
|
121
|
+
raise InvalidReceipt, "Subject token must be a Railtracks HMAC token"
|
|
122
|
+
end
|
|
123
|
+
unless payload["model"].match?(ErasureReceipt::MODEL_NAME)
|
|
124
|
+
raise InvalidReceipt, "Model name is not a loaded model name"
|
|
125
|
+
end
|
|
126
|
+
unless payload["schema_fingerprint"].match?(ErasureReceipt::HEX64)
|
|
127
|
+
raise InvalidReceipt, "Schema fingerprint must be a SHA-256 hex digest"
|
|
128
|
+
end
|
|
129
|
+
unless idempotency_key.is_a?(String) && idempotency_key.match?(ErasureReceipt::IDEMPOTENCY_KEY)
|
|
130
|
+
raise InvalidReceipt, "Idempotency key must be 8-128 URL-safe characters"
|
|
131
|
+
end
|
|
132
|
+
unless payload["completed_at"].match?(/\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z\z/)
|
|
133
|
+
raise InvalidReceipt, "Completion time must be a microsecond UTC timestamp"
|
|
134
|
+
end
|
|
135
|
+
return if payload["actions"].all? { |action| action["action"].in?(ACTIONS) }
|
|
136
|
+
|
|
137
|
+
raise InvalidReceipt, "Unknown erasure action in receipt"
|
|
138
|
+
end
|
|
139
|
+
end
|
|
140
|
+
end
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Railtracks
|
|
4
|
+
# Runs an erasure plan and records its receipt in the same transaction.
|
|
5
|
+
#
|
|
6
|
+
# The receipt write shares the erasure transaction, so if evidence cannot be
|
|
7
|
+
# written the erasure itself is rolled back. A plan that already has a receipt
|
|
8
|
+
# returns it without re-applying actions. Concurrent first-time callers both
|
|
9
|
+
# apply the same deterministic plan; the database keeps exactly one receipt.
|
|
10
|
+
#
|
|
11
|
+
# The target model comes from the wrapped execution or from an explicit
|
|
12
|
+
# `model:` argument. There is no default model.
|
|
13
|
+
class RecordedErasureExecution
|
|
14
|
+
class Error < StandardError; end
|
|
15
|
+
|
|
16
|
+
attr_reader :model
|
|
17
|
+
|
|
18
|
+
def initialize(execution:, store:, model: nil)
|
|
19
|
+
@execution = execution
|
|
20
|
+
@store = store
|
|
21
|
+
execution_model = execution.respond_to?(:model) ? execution.model : nil
|
|
22
|
+
@model = normalize_model(model || execution_model)
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
# Returns the persisted Railtracks::ErasureReceipt. The caller can check
|
|
26
|
+
# receipt.verified?(secret) and receipt.actions without trusting this call.
|
|
27
|
+
def call(subject_ref, model: @model, idempotency_key: nil)
|
|
28
|
+
raise ErasureExecution::SubjectNotFound, "Subject reference is required" if subject_ref.blank?
|
|
29
|
+
model = normalize_model(model)
|
|
30
|
+
raise ErasureExecution::ConfigurationError, "A target model is required" if model.nil?
|
|
31
|
+
|
|
32
|
+
subject_token = @execution.subject_token(subject_ref)
|
|
33
|
+
schema_fingerprint = @execution.schema_fingerprint
|
|
34
|
+
|
|
35
|
+
existing = @store.find(subject_token: subject_token, model: model, schema_fingerprint: schema_fingerprint)
|
|
36
|
+
return existing if existing
|
|
37
|
+
|
|
38
|
+
recorded = nil
|
|
39
|
+
ActiveRecord::Base.transaction do
|
|
40
|
+
receipt = @execution.call(subject_ref, model: model)
|
|
41
|
+
recorded = @store.record(
|
|
42
|
+
subject_token: receipt[:subject],
|
|
43
|
+
model: receipt[:model],
|
|
44
|
+
schema_fingerprint: receipt[:schema_fingerprint],
|
|
45
|
+
actions: receipt[:actions],
|
|
46
|
+
completed_at: receipt[:completed_at],
|
|
47
|
+
idempotency_key: idempotency_key
|
|
48
|
+
)
|
|
49
|
+
end
|
|
50
|
+
recorded || raise(Error, "Erasure completed without recording a receipt")
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
private
|
|
54
|
+
|
|
55
|
+
def normalize_model(model)
|
|
56
|
+
return nil if model.nil?
|
|
57
|
+
|
|
58
|
+
model.respond_to?(:name) ? model.name : model.to_s
|
|
59
|
+
end
|
|
60
|
+
end
|
|
61
|
+
end
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Erasure receipts are the durable evidence that a declared erasure plan ran.
|
|
4
|
+
# Two unique indexes protect that evidence:
|
|
5
|
+
#
|
|
6
|
+
# * the plan key (subject token, model name, schema fingerprint) ensures one
|
|
7
|
+
# receipt per executed plan, so a repeated request cannot inflate the record;
|
|
8
|
+
# * the idempotency key ensures one receipt per request, even if the plan
|
|
9
|
+
# changed between retries.
|
|
10
|
+
#
|
|
11
|
+
# Triggers reject UPDATE and DELETE for every row. PostgreSQL also rejects
|
|
12
|
+
# TRUNCATE while the table still holds evidence; SQLite has no TRUNCATE
|
|
13
|
+
# statement, so its delete trigger covers bulk removal. An empty PostgreSQL
|
|
14
|
+
# table may be reset, which keeps test setup simple without weakening the guard
|
|
15
|
+
# for real data.
|
|
16
|
+
#
|
|
17
|
+
# The engine ships this migration for the host to install with:
|
|
18
|
+
#
|
|
19
|
+
# bin/rails railtracks:install:migrations
|
|
20
|
+
# bin/rails db:migrate
|
|
21
|
+
#
|
|
22
|
+
# The host must keep a SQL structure dump (`schema_format = :sql`), because
|
|
23
|
+
# schema.rb cannot represent these triggers and constraints. A schema.rb build
|
|
24
|
+
# would silently lose the append-only boundary.
|
|
25
|
+
class CreateRailtracksErasureReceipts < ActiveRecord::Migration[7.2]
|
|
26
|
+
TABLE = :railtracks_erasure_receipts
|
|
27
|
+
|
|
28
|
+
def up
|
|
29
|
+
create_table TABLE do |t|
|
|
30
|
+
t.string :subject_token, null: false
|
|
31
|
+
t.string :model, null: false
|
|
32
|
+
t.string :schema_fingerprint, null: false
|
|
33
|
+
t.string :idempotency_key, null: false
|
|
34
|
+
if postgresql?
|
|
35
|
+
t.jsonb :actions, null: false, default: []
|
|
36
|
+
else
|
|
37
|
+
t.json :actions, null: false, default: []
|
|
38
|
+
end
|
|
39
|
+
t.datetime :completed_at, null: false
|
|
40
|
+
t.string :fingerprint, null: false
|
|
41
|
+
t.string :signature, null: false
|
|
42
|
+
|
|
43
|
+
t.timestamps
|
|
44
|
+
|
|
45
|
+
add_receipt_constraints(t)
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
add_index TABLE, [ :subject_token, :model, :schema_fingerprint ], unique: true,
|
|
49
|
+
name: "index_railtracks_erasure_receipts_on_plan_key"
|
|
50
|
+
add_index TABLE, :idempotency_key, unique: true,
|
|
51
|
+
name: "index_railtracks_erasure_receipts_on_idempotency_key"
|
|
52
|
+
|
|
53
|
+
if postgresql?
|
|
54
|
+
execute postgresql_triggers
|
|
55
|
+
else
|
|
56
|
+
execute sqlite_update_trigger
|
|
57
|
+
execute sqlite_delete_trigger
|
|
58
|
+
end
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
def down
|
|
62
|
+
if postgresql?
|
|
63
|
+
execute <<~SQL
|
|
64
|
+
DROP TRIGGER IF EXISTS railtracks_erasure_receipts_truncate_guard ON railtracks_erasure_receipts;
|
|
65
|
+
DROP TRIGGER IF EXISTS railtracks_erasure_receipts_row_append_only ON railtracks_erasure_receipts;
|
|
66
|
+
DROP FUNCTION IF EXISTS railtracks_erasure_receipts_truncate_guard();
|
|
67
|
+
DROP FUNCTION IF EXISTS railtracks_erasure_receipts_row_append_only();
|
|
68
|
+
SQL
|
|
69
|
+
else
|
|
70
|
+
execute "DROP TRIGGER IF EXISTS railtracks_erasure_receipts_delete_guard"
|
|
71
|
+
execute "DROP TRIGGER IF EXISTS railtracks_erasure_receipts_row_append_only"
|
|
72
|
+
end
|
|
73
|
+
drop_table TABLE
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
private
|
|
77
|
+
|
|
78
|
+
def postgresql?
|
|
79
|
+
connection.adapter_name == "PostgreSQL"
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
def add_receipt_constraints(table)
|
|
83
|
+
if postgresql?
|
|
84
|
+
table.check_constraint "subject_token ~ '^railtracks:[0-9a-f]{64}$'",
|
|
85
|
+
name: "railtracks_erasure_receipts_subject_token_format"
|
|
86
|
+
table.check_constraint "model ~ '^[A-Z][A-Za-z0-9_:]*$'",
|
|
87
|
+
name: "railtracks_erasure_receipts_model_format"
|
|
88
|
+
table.check_constraint "schema_fingerprint ~ '^[0-9a-f]{64}$'",
|
|
89
|
+
name: "railtracks_erasure_receipts_schema_fingerprint_format"
|
|
90
|
+
table.check_constraint "idempotency_key ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{7,127}$'",
|
|
91
|
+
name: "railtracks_erasure_receipts_idempotency_key_format"
|
|
92
|
+
table.check_constraint "fingerprint ~ '^[0-9a-f]{64}$'",
|
|
93
|
+
name: "railtracks_erasure_receipts_fingerprint_format"
|
|
94
|
+
table.check_constraint "signature ~ '^[0-9a-f]{64}$'",
|
|
95
|
+
name: "railtracks_erasure_receipts_signature_format"
|
|
96
|
+
table.check_constraint "jsonb_typeof(actions) = 'array'",
|
|
97
|
+
name: "railtracks_erasure_receipts_actions_array"
|
|
98
|
+
else
|
|
99
|
+
# SQLite has no regular expression operator. Length plus GLOB gives the
|
|
100
|
+
# same shape checks without a regular expression engine: the character
|
|
101
|
+
# class negation rejects any character outside the accepted set.
|
|
102
|
+
table.check_constraint "length(subject_token) = 75 AND subject_token GLOB 'railtracks:*' " \
|
|
103
|
+
"AND substr(subject_token, 12) NOT GLOB '*[^0-9a-f]*'",
|
|
104
|
+
name: "railtracks_erasure_receipts_subject_token_format"
|
|
105
|
+
table.check_constraint "model GLOB '[A-Z]*' AND model NOT GLOB '*[^A-Za-z0-9_:]*'",
|
|
106
|
+
name: "railtracks_erasure_receipts_model_format"
|
|
107
|
+
table.check_constraint "length(schema_fingerprint) = 64 AND schema_fingerprint NOT GLOB '*[^0-9a-f]*'",
|
|
108
|
+
name: "railtracks_erasure_receipts_schema_fingerprint_format"
|
|
109
|
+
table.check_constraint "length(idempotency_key) BETWEEN 8 AND 128 " \
|
|
110
|
+
"AND idempotency_key GLOB '[A-Za-z0-9]*' AND idempotency_key NOT GLOB '*[^A-Za-z0-9._:-]*'",
|
|
111
|
+
name: "railtracks_erasure_receipts_idempotency_key_format"
|
|
112
|
+
table.check_constraint "length(fingerprint) = 64 AND fingerprint NOT GLOB '*[^0-9a-f]*'",
|
|
113
|
+
name: "railtracks_erasure_receipts_fingerprint_format"
|
|
114
|
+
table.check_constraint "length(signature) = 64 AND signature NOT GLOB '*[^0-9a-f]*'",
|
|
115
|
+
name: "railtracks_erasure_receipts_signature_format"
|
|
116
|
+
table.check_constraint "json_valid(actions) AND json_type(actions) = 'array'",
|
|
117
|
+
name: "railtracks_erasure_receipts_actions_array"
|
|
118
|
+
end
|
|
119
|
+
end
|
|
120
|
+
|
|
121
|
+
def postgresql_triggers
|
|
122
|
+
<<~SQL
|
|
123
|
+
CREATE FUNCTION railtracks_erasure_receipts_row_append_only()
|
|
124
|
+
RETURNS trigger
|
|
125
|
+
LANGUAGE plpgsql
|
|
126
|
+
AS $$
|
|
127
|
+
BEGIN
|
|
128
|
+
RAISE EXCEPTION 'railtracks_erasure_receipts is append-only (% rejected)', TG_OP
|
|
129
|
+
USING ERRCODE = 'restrict_violation';
|
|
130
|
+
END;
|
|
131
|
+
$$;
|
|
132
|
+
|
|
133
|
+
CREATE TRIGGER railtracks_erasure_receipts_row_append_only
|
|
134
|
+
BEFORE UPDATE OR DELETE ON railtracks_erasure_receipts
|
|
135
|
+
FOR EACH ROW EXECUTE FUNCTION railtracks_erasure_receipts_row_append_only();
|
|
136
|
+
|
|
137
|
+
CREATE FUNCTION railtracks_erasure_receipts_truncate_guard()
|
|
138
|
+
RETURNS trigger
|
|
139
|
+
LANGUAGE plpgsql
|
|
140
|
+
AS $$
|
|
141
|
+
BEGIN
|
|
142
|
+
IF EXISTS (SELECT 1 FROM railtracks_erasure_receipts) THEN
|
|
143
|
+
RAISE EXCEPTION 'railtracks_erasure_receipts holds evidence and cannot be truncated'
|
|
144
|
+
USING ERRCODE = 'restrict_violation';
|
|
145
|
+
END IF;
|
|
146
|
+
RETURN NULL;
|
|
147
|
+
END;
|
|
148
|
+
$$;
|
|
149
|
+
|
|
150
|
+
CREATE TRIGGER railtracks_erasure_receipts_truncate_guard
|
|
151
|
+
BEFORE TRUNCATE ON railtracks_erasure_receipts
|
|
152
|
+
FOR EACH STATEMENT EXECUTE FUNCTION railtracks_erasure_receipts_truncate_guard();
|
|
153
|
+
SQL
|
|
154
|
+
end
|
|
155
|
+
|
|
156
|
+
def sqlite_update_trigger
|
|
157
|
+
<<~SQL
|
|
158
|
+
CREATE TRIGGER railtracks_erasure_receipts_row_append_only
|
|
159
|
+
BEFORE UPDATE ON railtracks_erasure_receipts
|
|
160
|
+
FOR EACH ROW
|
|
161
|
+
BEGIN
|
|
162
|
+
SELECT RAISE(ABORT, 'railtracks_erasure_receipts is append-only (UPDATE rejected)');
|
|
163
|
+
END
|
|
164
|
+
SQL
|
|
165
|
+
end
|
|
166
|
+
|
|
167
|
+
def sqlite_delete_trigger
|
|
168
|
+
<<~SQL
|
|
169
|
+
CREATE TRIGGER railtracks_erasure_receipts_delete_guard
|
|
170
|
+
BEFORE DELETE ON railtracks_erasure_receipts
|
|
171
|
+
FOR EACH ROW
|
|
172
|
+
BEGIN
|
|
173
|
+
SELECT RAISE(ABORT, 'railtracks_erasure_receipts is append-only (DELETE rejected)');
|
|
174
|
+
END
|
|
175
|
+
SQL
|
|
176
|
+
end
|
|
177
|
+
end
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
# Configuration
|
|
2
|
+
|
|
3
|
+
Railtracks is opt-in. The initializer generated by
|
|
4
|
+
`bin/rails generate railtracks:install` is empty until you enable a track.
|
|
5
|
+
|
|
6
|
+
## The retention track
|
|
7
|
+
|
|
8
|
+
```ruby
|
|
9
|
+
# config/initializers/railtracks.rb
|
|
10
|
+
Rails.application.config.to_prepare do
|
|
11
|
+
Railtracks.configure do |config|
|
|
12
|
+
config.track :retention do |retention|
|
|
13
|
+
retention.receipt_secret = Rails.application.credentials.railtracks_secret
|
|
14
|
+
retention.registry = Railtracks::Registry.from_yaml(
|
|
15
|
+
Rails.root.join("config/railtracks.yml")
|
|
16
|
+
)
|
|
17
|
+
retention.model_classes = [ User, Note ]
|
|
18
|
+
retention.target_model = User
|
|
19
|
+
end
|
|
20
|
+
end
|
|
21
|
+
end
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
| Setting | Required | Meaning |
|
|
25
|
+
| --- | --- | --- |
|
|
26
|
+
| `receipt_secret` | yes | Secret used for subject tokens and receipt HMACs. A blank value is rejected. |
|
|
27
|
+
| `registry` | yes | A `Railtracks::Registry` built from YAML or explicit declarations. |
|
|
28
|
+
| `model_classes` | yes | Active Record model classes under management. Used by `SchemaAudit` and `SchemaFingerprint`. |
|
|
29
|
+
| `target_model` | for erasure | Default model erased by `Railtracks.retention.execution` and `recorded_execution`. Must be one of `model_classes`. |
|
|
30
|
+
|
|
31
|
+
`Railtracks.configure` calls `validate!` immediately. The retention track fails
|
|
32
|
+
at boot when:
|
|
33
|
+
|
|
34
|
+
- `registry` is missing or is not a `Railtracks::Registry`;
|
|
35
|
+
- `receipt_secret` is nil, blank or whitespace;
|
|
36
|
+
- `model_classes` is empty or contains something that is not an Active Record
|
|
37
|
+
model class;
|
|
38
|
+
- `target_model` is set but is not included in `model_classes`.
|
|
39
|
+
|
|
40
|
+
Services also fail closed when called without a target model, so removing
|
|
41
|
+
`target_model` cannot silently fall back to a demo class.
|
|
42
|
+
|
|
43
|
+
## YAML registry
|
|
44
|
+
|
|
45
|
+
```yaml
|
|
46
|
+
declarations:
|
|
47
|
+
- model: User
|
|
48
|
+
column: email
|
|
49
|
+
category: contact
|
|
50
|
+
action: pseudonymize
|
|
51
|
+
retention: 30 days
|
|
52
|
+
|
|
53
|
+
- model: User
|
|
54
|
+
column: name
|
|
55
|
+
category: contact
|
|
56
|
+
action: delete
|
|
57
|
+
retention: 30 days
|
|
58
|
+
|
|
59
|
+
- model: User
|
|
60
|
+
column: id
|
|
61
|
+
category: identifier
|
|
62
|
+
action: retain
|
|
63
|
+
retention: 7 years
|
|
64
|
+
justification: Primary key keeps the audit row linkable
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
| Key | Accepted values |
|
|
68
|
+
| --- | --- |
|
|
69
|
+
| `model` | A loaded class name such as `User` |
|
|
70
|
+
| `column` | A real database column on that model |
|
|
71
|
+
| `category` | A lowercase annotation such as `contact` or `identifier` |
|
|
72
|
+
| `action` | `delete`, `pseudonymize` or `retain` |
|
|
73
|
+
| `retention` | Positive integer plus `day(s)`, `week(s)`, `month(s)` or `year(s)`, at most 100 years |
|
|
74
|
+
| `justification` | Required and non-blank when `action` is `retain` |
|
|
75
|
+
|
|
76
|
+
YAML is loaded with `YAML.safe_load_file` and aliases disabled. Unknown keys are
|
|
77
|
+
not treated as code, but every declared column must exist on the loaded model.
|
|
78
|
+
|
|
79
|
+
You can build the registry directly:
|
|
80
|
+
|
|
81
|
+
```ruby
|
|
82
|
+
Railtracks::Registry.new([
|
|
83
|
+
{ model: "User", column: "email", category: :contact,
|
|
84
|
+
action: :pseudonymize, retention: "30 days", justification: nil }
|
|
85
|
+
])
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
## The configured services
|
|
89
|
+
|
|
90
|
+
`Railtracks.retention` returns a `Railtracks::Retention` bound to the current
|
|
91
|
+
configuration:
|
|
92
|
+
|
|
93
|
+
```ruby
|
|
94
|
+
retention = Railtracks.retention
|
|
95
|
+
|
|
96
|
+
retention.registry # Railtracks::Registry
|
|
97
|
+
retention.receipt_secret # the configured secret
|
|
98
|
+
retention.model_classes # [User, Note]
|
|
99
|
+
retention.target_model # "User"
|
|
100
|
+
|
|
101
|
+
retention.store # Railtracks::ReceiptStore
|
|
102
|
+
retention.execution # Railtracks::ErasureExecution for target_model
|
|
103
|
+
retention.recorded_execution# Railtracks::RecordedErasureExecution
|
|
104
|
+
retention.due_for_erasure # Railtracks::DueForErasure
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Each factory accepts an override where it makes sense:
|
|
108
|
+
|
|
109
|
+
```ruby
|
|
110
|
+
Railtracks.retention.execution(model: Account).call("subject-123")
|
|
111
|
+
Railtracks.retention.due_for_erasure(now: Time.utc(2026, 12, 1)).call(limit: 50)
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
`Railtracks.retention` itself raises `Railtracks::Configuration::Error` when the
|
|
115
|
+
retention track is not enabled.
|
|
116
|
+
|
|
117
|
+
## Reloading in development
|
|
118
|
+
|
|
119
|
+
`Rails.application.config.to_prepare` is the safest place for the initializer
|
|
120
|
+
when `model_classes` references application classes. It re-runs after code
|
|
121
|
+
reloads and keeps the model list current. The demo application in this
|
|
122
|
+
repository uses the same pattern.
|
|
123
|
+
|
|
124
|
+
## Resetting configuration in tests
|
|
125
|
+
|
|
126
|
+
```ruby
|
|
127
|
+
Railtracks.reset! # drops the configuration and the memoized retention object
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
Call it before rebuilding a configuration in a test. Restore the real
|
|
131
|
+
configuration in teardown, or keep the test confined to
|
|
132
|
+
`Railtracks::Configuration.new`.
|
data/docs/install.md
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# Install
|
|
2
|
+
|
|
3
|
+
## Requirements
|
|
4
|
+
|
|
5
|
+
- Ruby 3.2, 3.3 or 3.4.
|
|
6
|
+
- Rails 7.2, 8.0 or 8.1.
|
|
7
|
+
- SQLite for development and tests, or PostgreSQL for a durable evidence store.
|
|
8
|
+
The engine migration detects the adapter and installs the matching check
|
|
9
|
+
constraints and append-only triggers.
|
|
10
|
+
|
|
11
|
+
## Add the gem
|
|
12
|
+
|
|
13
|
+
```ruby
|
|
14
|
+
# Gemfile
|
|
15
|
+
gem "railtracks"
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
```sh
|
|
19
|
+
bundle install
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Generate the initializer and migration
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
bin/rails generate railtracks:install
|
|
26
|
+
bin/rails railtracks:install:migrations
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
The install generator writes `config/initializers/railtracks.rb`. The migration
|
|
30
|
+
copy step is what creates `railtracks_erasure_receipts` in the host.
|
|
31
|
+
|
|
32
|
+
## Keep SQL structure dumps
|
|
33
|
+
|
|
34
|
+
The append-only boundary lives in database objects that `schema.rb` cannot
|
|
35
|
+
express: check constraints, partial uniqueness rules and triggers. Use:
|
|
36
|
+
|
|
37
|
+
```ruby
|
|
38
|
+
# config/application.rb
|
|
39
|
+
config.active_record.schema_format = :sql
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Load the correct dump for the adapter. A host running both adapters in different
|
|
43
|
+
environments should select the dump explicitly:
|
|
44
|
+
|
|
45
|
+
```ruby
|
|
46
|
+
# development and test on SQLite; production on PostgreSQL
|
|
47
|
+
unless Rails.env.production?
|
|
48
|
+
ENV["SCHEMA"] ||= "db/sqlite_structure.sql" if ENV.fetch("RAILTRACKS_DB_ADAPTER", "sqlite3") == "sqlite3"
|
|
49
|
+
end
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
A `schema.rb` build silently loses the triggers. The model tests and the
|
|
53
|
+
database-boundary tests in this repository fail when the triggers are missing,
|
|
54
|
+
so keep them in CI.
|
|
55
|
+
|
|
56
|
+
## Run the migration
|
|
57
|
+
|
|
58
|
+
```sh
|
|
59
|
+
bin/rails db:migrate
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
The migration is adapter-aware:
|
|
63
|
+
|
|
64
|
+
- **SQLite**: `json` column, `GLOB`/`length` check constraints, update and
|
|
65
|
+
delete triggers.
|
|
66
|
+
- **PostgreSQL**: `jsonb` column, regular-expression check constraints, a
|
|
67
|
+
row-level `UPDATE`/`DELETE` trigger, and a statement-level `TRUNCATE` guard.
|
|
68
|
+
|
|
69
|
+
Verify the table exists and is protected:
|
|
70
|
+
|
|
71
|
+
```sh
|
|
72
|
+
bin/rails runner 'puts Railtracks::ErasureReceipt.table_name'
|
|
73
|
+
# railtracks_erasure_receipts
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## Configure a track
|
|
77
|
+
|
|
78
|
+
Nothing is active until the track is enabled. See
|
|
79
|
+
[configuration](configuration.md).
|
|
80
|
+
|
|
81
|
+
## Troubleshooting
|
|
82
|
+
|
|
83
|
+
- **`Migrations are pending` after adding the gem**: run
|
|
84
|
+
`bin/rails railtracks:install:migrations` and `bin/rails db:migrate`.
|
|
85
|
+
- **Triggers missing after a schema load**: the host loaded `schema.rb` instead
|
|
86
|
+
of a SQL dump. Set `config.active_record.schema_format = :sql` and point
|
|
87
|
+
`SCHEMA` at the right dump.
|
|
88
|
+
- **`The retention track requires ...` at boot**: `Railtracks.configure`
|
|
89
|
+
validates the registry, secret, model classes and target model. Fix the
|
|
90
|
+
initializer rather than disabling validation.
|
data/docs/limits.md
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
# Limits
|
|
2
|
+
|
|
3
|
+
Railtracks is a technical control, not legal advice. It produces evidence about
|
|
4
|
+
what a specific Rails application executed against a specific database. It does
|
|
5
|
+
not decide whether a declaration, retention period or erasure is lawful.
|
|
6
|
+
|
|
7
|
+
## Scope of a declaration
|
|
8
|
+
|
|
9
|
+
- Coverage is checked only against the model classes passed to `SchemaAudit`,
|
|
10
|
+
`ErasureExecution` or the demo association adapter. A model that is never
|
|
11
|
+
passed is invisible to the audit. Declaring every column of `User` does not
|
|
12
|
+
prove that `Invoice`, `AuditLog`, a sibling service or a warehouse was
|
|
13
|
+
considered.
|
|
14
|
+
- The declaration set is human input. A field classified as `retain` without a
|
|
15
|
+
good reason, or a personal field omitted from the model list, produces
|
|
16
|
+
internally consistent evidence for the wrong plan.
|
|
17
|
+
- `category` is an annotation. It does not enforce a policy and is not part of
|
|
18
|
+
the schema fingerprint.
|
|
19
|
+
- Execution covers one target model at a time. The gem does not discover
|
|
20
|
+
association graphs, polymorphic relations, join tables or denormalised copies.
|
|
21
|
+
`AssociationErasureExecution` in the demo application is a concrete adapter
|
|
22
|
+
for `User has_many :notes`, not a generic graph walker.
|
|
23
|
+
|
|
24
|
+
## What erasure means here
|
|
25
|
+
|
|
26
|
+
- `delete` writes `NULL` to the declared column. It does not delete the row.
|
|
27
|
+
Other columns, the primary key and any undeclared data remain.
|
|
28
|
+
- `pseudonymize` writes a deterministic value derived from the secret and the
|
|
29
|
+
row. It removes the original value from the current row, but the result is a
|
|
30
|
+
stable identifier: the same input produces the same output, so it can be
|
|
31
|
+
linked across runs by anyone who can compute it. It is pseudonymisation, not
|
|
32
|
+
anonymisation.
|
|
33
|
+
- SQLite may retain old bytes in free pages or a write-ahead log. PostgreSQL
|
|
34
|
+
keeps old tuple versions until vacuum. Filesystem snapshots, backups, binary
|
|
35
|
+
logs and replicas are outside this application. The SQL row no longer returns
|
|
36
|
+
the value; that is not physical media sanitisation.
|
|
37
|
+
- No ActiveStorage attachment, external API, search index, cache, queue payload
|
|
38
|
+
or third-party processor is erased. Those need separate adapters and separate
|
|
39
|
+
evidence.
|
|
40
|
+
- `DueForErasure` reports due receipts; it does not erase anything and does not
|
|
41
|
+
schedule work.
|
|
42
|
+
|
|
43
|
+
## Integrity and trust
|
|
44
|
+
|
|
45
|
+
- The HMAC detects a changed row only if the verifier has the secret. Someone
|
|
46
|
+
who controls the database can drop triggers, edit rows and recompute the HMAC.
|
|
47
|
+
The receipt is tamper-evident under the stated secret and database
|
|
48
|
+
assumptions, not tamper-proof against a privileged operator.
|
|
49
|
+
- The triggers are database objects. A migration, a superuser or a
|
|
50
|
+
`DROP TRIGGER` can remove them.
|
|
51
|
+
- `readonly?` and the model validations are application guards. Raw SQL and
|
|
52
|
+
direct database access are governed by database constraints and triggers.
|
|
53
|
+
- Secret rotation invalidates receipts created with the old secret. There is no
|
|
54
|
+
key ID, key ring or historical verification path.
|
|
55
|
+
- The secret is supplied by the caller. Railtracks does not provide a KMS, HSM,
|
|
56
|
+
envelope encryption or secret storage.
|
|
57
|
+
- Receipts store model and column names and action outcomes. They do not store
|
|
58
|
+
field values or the original subject reference, but column names can reveal
|
|
59
|
+
schema structure.
|
|
60
|
+
|
|
61
|
+
## Retention semantics
|
|
62
|
+
|
|
63
|
+
- Durations are fixed seconds: one month is 30 days, one year is 365 days. They
|
|
64
|
+
are not calendar months or years, and leap days are not modelled.
|
|
65
|
+
- A due date is computed from the current declaration set, not from a copy in
|
|
66
|
+
the receipt. Changing a retention period changes future answers for existing
|
|
67
|
+
receipts. Comparing the receipt's schema fingerprint with the current
|
|
68
|
+
fingerprint is a manual step.
|
|
69
|
+
- The clock is the application's clock. A wrong system clock produces a wrong
|
|
70
|
+
due date and a wrong `completed_at`.
|
|
71
|
+
- The due report is bounded: the default limit is 100 and the maximum is 1,000
|
|
72
|
+
per bucket. If evidence is truncated, `Report#complete?` is false.
|
|
73
|
+
- `undatable` receipts (the model is no longer declared) and `unverifiable`
|
|
74
|
+
receipts (the row fails its own digest check) are reported instead of being
|
|
75
|
+
dropped. They still make the report incomplete.
|
|
76
|
+
|
|
77
|
+
## Platform limits
|
|
78
|
+
|
|
79
|
+
- SQLite is the local development, demo and test adapter. It has no roles,
|
|
80
|
+
`TRUNCATE` or PostgreSQL trigger functions; its delete trigger covers bulk
|
|
81
|
+
removal, but it does not provide the same operational separation as a
|
|
82
|
+
PostgreSQL deployment.
|
|
83
|
+
- The database boundary depends on SQL structure dumps. A deployment that loads
|
|
84
|
+
only `schema.rb` loses the triggers and check constraints.
|
|
85
|
+
- There is no authenticated web endpoint, operator console, multi-tenant
|
|
86
|
+
authorization or audit of who called the service.
|
|
87
|
+
- There is no background job integration with the same receipt guarantees, no
|
|
88
|
+
signed export bundle and no scheduler that runs erasures.
|
|
89
|
+
- The tests cover model behaviour and the database boundary on SQLite and
|
|
90
|
+
PostgreSQL. They do not include sustained concurrency, large data volumes,
|
|
91
|
+
disaster recovery or key rotation.
|