standard_audit 0.5.0 → 0.7.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/CHANGELOG.md +57 -0
- data/{MIT-LICENSE → LICENSE} +3 -1
- data/README.md +91 -2
- data/app/models/standard_audit/audit_log.rb +77 -38
- data/lib/generators/standard_audit/install/templates/initializer.rb.erb +46 -4
- data/lib/standard_audit/checks/retention.rb +58 -0
- data/lib/standard_audit/configuration.rb +80 -2
- data/lib/standard_audit/metadata_filter.rb +155 -0
- data/lib/standard_audit/reference_preloading.rb +298 -0
- data/lib/standard_audit/rspec.rb +17 -3
- data/lib/standard_audit/sensitive_keys_dry_run.rb +177 -0
- data/lib/standard_audit/subscriber.rb +5 -3
- data/lib/standard_audit/version.rb +1 -1
- data/lib/standard_audit.rb +48 -7
- data/lib/tasks/standard_audit_tasks.rake +41 -0
- metadata +6 -2
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
module StandardAudit
|
|
2
|
+
# The single implementation of sensitive-key redaction for audit metadata.
|
|
3
|
+
#
|
|
4
|
+
# There used to be two: one in `StandardAudit.record` and one in
|
|
5
|
+
# `Subscriber#extract_metadata`. They had already diverged — the subscriber
|
|
6
|
+
# copy did not subtract `RESERVED_METADATA_KEYS`, so an app that (reasonably)
|
|
7
|
+
# added `:_tags` to `sensitive_keys` got the reserved key preserved on the
|
|
8
|
+
# `record` path and stripped on the `ActiveSupport::Notifications` path. Two
|
|
9
|
+
# copies of a security filter drifting apart is exactly the failure mode
|
|
10
|
+
# worth designing out, so both paths now call here.
|
|
11
|
+
#
|
|
12
|
+
# The divergence is resolved in favour of `record`'s behaviour: reserved keys
|
|
13
|
+
# are subtracted from the sensitive set and can never be filtered.
|
|
14
|
+
#
|
|
15
|
+
# == Matching
|
|
16
|
+
#
|
|
17
|
+
# A key is redacted when it matches `config.sensitive_keys` **exactly** (by
|
|
18
|
+
# name, string/symbol insensitive) or matches one of
|
|
19
|
+
# `config.sensitive_key_patterns` (Regexps, always applied), unless it is
|
|
20
|
+
# listed in `config.sensitive_key_exceptions` or is a reserved key.
|
|
21
|
+
#
|
|
22
|
+
# == Why there is no substring mode
|
|
23
|
+
#
|
|
24
|
+
# Matching `sensitive_keys` by substring instead of exactly is the obvious
|
|
25
|
+
# "fix" for `client_secret` not matching `:secret`, and it is a trap. Against
|
|
26
|
+
# the current default key list it would strip real audit content across the
|
|
27
|
+
# estate:
|
|
28
|
+
#
|
|
29
|
+
# :token => input_tokens, output_tokens (live LLM cost accounting),
|
|
30
|
+
# token_digest (rendered in a staff audit UI)
|
|
31
|
+
# :password => password_reset_sent_at, onepassword
|
|
32
|
+
# :authorization => authorization_endpoint
|
|
33
|
+
#
|
|
34
|
+
# Audit rows are append-only, so a bad default cannot be undone — the content
|
|
35
|
+
# is simply never written. `sensitive_key_patterns` is the supported tool
|
|
36
|
+
# instead: `/secret/i` solves the motivating `client_secret` case exactly,
|
|
37
|
+
# opt-in and per-app, and `rake standard_audit:sensitive_keys:dry_run` turns
|
|
38
|
+
# "is this rule safe for my data?" into a command rather than a guess.
|
|
39
|
+
class MetadataFilter
|
|
40
|
+
# Raised when metadata is neither nil nor hash-like. Deliberately a raise
|
|
41
|
+
# rather than a pass-through: this filter **fails closed**. An
|
|
42
|
+
# `ActionController::Parameters` is not a `Hash`, and letting an unrecognised
|
|
43
|
+
# object through unfiltered would write raw params — passwords included —
|
|
44
|
+
# into an append-only row. Pre-0.7.0 the same input blew up with
|
|
45
|
+
# `NoMethodError` on `#reject`, so raising preserves the outcome while
|
|
46
|
+
# naming the cause.
|
|
47
|
+
class UnfilterableMetadataError < ArgumentError; end
|
|
48
|
+
|
|
49
|
+
class << self
|
|
50
|
+
def call(metadata, config: StandardAudit.config)
|
|
51
|
+
new(config: config).call(metadata)
|
|
52
|
+
end
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
def initialize(config: StandardAudit.config)
|
|
56
|
+
@config = config
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
# Filters anything hash-like, not just `Hash` — `ActionController::Parameters`
|
|
60
|
+
# and other `each_pair`-able wrappers are filtered rather than waved
|
|
61
|
+
# through. `nil` passes (there is nothing to leak); anything else raises.
|
|
62
|
+
#
|
|
63
|
+
# Descends into nested Hashes (and Hashes inside Arrays) only when
|
|
64
|
+
# `config.filter_nested_metadata` is true. Reserved keys are preserved and
|
|
65
|
+
# their values are left entirely alone, **at every depth** — `_tags` and
|
|
66
|
+
# `_source` are gem-owned, not host payload, and immunity that held only at
|
|
67
|
+
# the top level would be a confusing half-guarantee.
|
|
68
|
+
def call(metadata)
|
|
69
|
+
return nil if metadata.nil?
|
|
70
|
+
|
|
71
|
+
unless hash_like?(metadata)
|
|
72
|
+
raise UnfilterableMetadataError,
|
|
73
|
+
"audit metadata must be nil or hash-like (got #{metadata.class}); " \
|
|
74
|
+
"refusing to write it unfiltered"
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
filtered = metadata.reject { |key, _| filter?(key) }
|
|
78
|
+
return filtered unless @config.filter_nested_metadata
|
|
79
|
+
|
|
80
|
+
filter_values(filtered)
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
# True when `key` would be redacted from metadata. Public so hosts (and the
|
|
84
|
+
# dry-run tooling) can ask the question without writing a row.
|
|
85
|
+
def filter?(key)
|
|
86
|
+
key = key.to_s
|
|
87
|
+
|
|
88
|
+
# `_tags` and `_source` are owned by EventSubscriber and are never
|
|
89
|
+
# stripped, even if a consumer lists them in `sensitive_keys`.
|
|
90
|
+
return false if StandardAudit::RESERVED_METADATA_KEYS.include?(key)
|
|
91
|
+
return false if exception?(key)
|
|
92
|
+
|
|
93
|
+
sensitive_keys.include?(key) || sensitive_key_patterns.any? { |pattern| pattern.match?(key) }
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
private
|
|
97
|
+
|
|
98
|
+
def hash_like?(value)
|
|
99
|
+
value.respond_to?(:each_pair) && value.respond_to?(:reject)
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
# Rewrites each value in place on the already-rejected copy. In place
|
|
103
|
+
# because `transform_values` is not guaranteed across every hash-like
|
|
104
|
+
# wrapper, whereas `[]=` is.
|
|
105
|
+
def filter_values(hash)
|
|
106
|
+
hash.each_pair do |key, value|
|
|
107
|
+
# Reserved subtree: immune at every depth, never descended into.
|
|
108
|
+
next if StandardAudit::RESERVED_METADATA_KEYS.include?(key.to_s)
|
|
109
|
+
|
|
110
|
+
replacement = filter_descendant(value)
|
|
111
|
+
hash[key] = replacement unless replacement.equal?(value)
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
hash
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
def filter_descendant(value)
|
|
118
|
+
if hash_like?(value)
|
|
119
|
+
filter_values(value.reject { |key, _| filter?(key) })
|
|
120
|
+
elsif value.is_a?(Array)
|
|
121
|
+
value.map { |element| filter_descendant(element) }
|
|
122
|
+
else
|
|
123
|
+
value
|
|
124
|
+
end
|
|
125
|
+
end
|
|
126
|
+
|
|
127
|
+
def sensitive_keys
|
|
128
|
+
@sensitive_keys ||= @config.sensitive_keys.map(&:to_s) - StandardAudit::RESERVED_METADATA_KEYS
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
# A String entry is read as a Regexp source, so the rake task (and a
|
|
132
|
+
# `SENSITIVE_KEY_PATTERNS` env var) can pass one through without eval.
|
|
133
|
+
def sensitive_key_patterns
|
|
134
|
+
@sensitive_key_patterns ||= Array(@config.sensitive_key_patterns).map do |pattern|
|
|
135
|
+
pattern.is_a?(Regexp) ? pattern : Regexp.new(pattern.to_s)
|
|
136
|
+
end
|
|
137
|
+
end
|
|
138
|
+
|
|
139
|
+
def exception?(key)
|
|
140
|
+
exact_exceptions.include?(key) || pattern_exceptions.any? { |pattern| pattern.match?(key) }
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
def exceptions
|
|
144
|
+
@exceptions ||= Array(@config.sensitive_key_exceptions).partition { |entry| entry.is_a?(Regexp) }
|
|
145
|
+
end
|
|
146
|
+
|
|
147
|
+
def pattern_exceptions
|
|
148
|
+
exceptions.first
|
|
149
|
+
end
|
|
150
|
+
|
|
151
|
+
def exact_exceptions
|
|
152
|
+
@exact_exceptions ||= exceptions.last.map(&:to_s)
|
|
153
|
+
end
|
|
154
|
+
end
|
|
155
|
+
end
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
require "cgi"
|
|
2
|
+
require "active_support/concern"
|
|
3
|
+
|
|
4
|
+
module StandardAudit
|
|
5
|
+
# Batch resolution of the GlobalID-backed `actor` / `target` / `scope`
|
|
6
|
+
# references on a page of audit rows, plus the per-row memo the readers
|
|
7
|
+
# consult.
|
|
8
|
+
#
|
|
9
|
+
# Why this exists: `AuditLog#actor` resolves `actor_gid` through
|
|
10
|
+
# `GlobalID::Locator.locate`, which is one query per row. Rendering N rows
|
|
11
|
+
# that each read `actor` and `target` issues O(N) lookups — an N+1 that
|
|
12
|
+
# Prosopite fails in every consuming app. Before this concern existed, apps
|
|
13
|
+
# worked around it by defining their own `preloaded_actor=` writer (or
|
|
14
|
+
# reaching into `@preloaded_actor` with `instance_variable_set`) and
|
|
15
|
+
# hand-rolling a per-type whitelist loader.
|
|
16
|
+
#
|
|
17
|
+
# == Memo semantics
|
|
18
|
+
#
|
|
19
|
+
# The memo is a Hash consulted with `key?`, not a pair of ivars checked with
|
|
20
|
+
# `defined?`. That distinction matters: a reference that was preloaded but
|
|
21
|
+
# whose record has since been deleted memoizes `nil`, and reads back as
|
|
22
|
+
# `nil` *without* falling through to a query. "Preloaded, and the answer is
|
|
23
|
+
# nothing" is therefore distinct from "not preloaded".
|
|
24
|
+
#
|
|
25
|
+
# `actor=` / `target=` / `scope=` populate the memo too, since the writer
|
|
26
|
+
# already holds the record. `reload` clears it.
|
|
27
|
+
#
|
|
28
|
+
# == Batched writes
|
|
29
|
+
#
|
|
30
|
+
# `StandardAudit.batch { ... }` flushes through `insert_all!` and never
|
|
31
|
+
# instantiates an AuditLog, so nothing in this concern runs on that path —
|
|
32
|
+
# neither the memo nor the writers. It is a no-op for batched writes by
|
|
33
|
+
# construction, not by accident.
|
|
34
|
+
module ReferencePreloading
|
|
35
|
+
extend ActiveSupport::Concern
|
|
36
|
+
|
|
37
|
+
# The GlobalID-backed reference columns. `scope` is preloadable but not in
|
|
38
|
+
# the default `refs:` set, since most read surfaces render actor/target
|
|
39
|
+
# only.
|
|
40
|
+
REFERENCES = %i[actor target scope].freeze
|
|
41
|
+
|
|
42
|
+
DEFAULT_REFS = %i[actor target].freeze
|
|
43
|
+
|
|
44
|
+
class_methods do
|
|
45
|
+
# Resolves the given references for a whole collection of audit logs in a
|
|
46
|
+
# fixed number of queries (one per distinct stored `*_type`), then
|
|
47
|
+
# memoizes the result on each row.
|
|
48
|
+
#
|
|
49
|
+
# AuditLog.preload_references(
|
|
50
|
+
# logs,
|
|
51
|
+
# refs: %i[actor target],
|
|
52
|
+
# only: [Account, Profile, Order],
|
|
53
|
+
# includes: { "Profile" => [:account], "Order" => [:user] }
|
|
54
|
+
# )
|
|
55
|
+
#
|
|
56
|
+
# [refs:] Which references to resolve. Defaults to `%i[actor target]`.
|
|
57
|
+
# [only:] Optional whitelist of permitted classes. See the note below —
|
|
58
|
+
# this is matched against the *stored type string*, so it is
|
|
59
|
+
# a stricter gate than `GlobalID::Locator`'s own `:only`.
|
|
60
|
+
# [includes:] Either a uniform Active Record `includes` spec applied to
|
|
61
|
+
# every type, or a per-type Hash keyed by class name String
|
|
62
|
+
# or Class constant (e.g. `{ "Profile" => [:account] }`).
|
|
63
|
+
# A Hash counts as per-type only when *every* key is a String
|
|
64
|
+
# or a Module; `{ account: :identifiers }` is therefore read
|
|
65
|
+
# as a uniform nested-includes spec, as you would expect.
|
|
66
|
+
#
|
|
67
|
+
# == Why `only:` is matched on the stored string
|
|
68
|
+
#
|
|
69
|
+
# `GlobalID::Locator`'s `:only` option is evaluated as
|
|
70
|
+
# `gid.model_class <= klass`, which means it *constantizes the stored
|
|
71
|
+
# type string before deciding whether it was allowed*. That is the wrong
|
|
72
|
+
# order for audit rows, whose type strings are historical: a class that
|
|
73
|
+
# has since been renamed or removed raises `NameError` rather than being
|
|
74
|
+
# filtered out. So this method filters on the stored `*_type` string
|
|
75
|
+
# first, by class name, and only then hands the surviving gids to
|
|
76
|
+
# `locate_many` (still passing `only:` as a second gate).
|
|
77
|
+
#
|
|
78
|
+
# The consequence is that `only:` does **not** expand to subclasses or
|
|
79
|
+
# to modules the way GlobalID's does — list every concrete class whose
|
|
80
|
+
# name you expect to see in `actor_type` / `target_type`. Deny-by-default
|
|
81
|
+
# is the safe direction for a whitelist.
|
|
82
|
+
#
|
|
83
|
+
# A reference whose type is not in `only:` memoizes `nil`, so it reads
|
|
84
|
+
# back as nil without a query rather than silently re-N+1ing.
|
|
85
|
+
#
|
|
86
|
+
# Returns the logs as an Array.
|
|
87
|
+
def preload_references(logs, refs: DEFAULT_REFS, only: nil, includes: nil)
|
|
88
|
+
logs = logs.to_a
|
|
89
|
+
return logs if logs.empty?
|
|
90
|
+
|
|
91
|
+
Array(refs).each do |ref|
|
|
92
|
+
ref = ref.to_sym
|
|
93
|
+
unless REFERENCES.include?(ref)
|
|
94
|
+
raise ArgumentError, "unknown audit reference #{ref.inspect} (expected one of #{REFERENCES.inspect})"
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
preload_one_reference(logs, ref, only: only, includes: includes)
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
logs
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
# Extracts the model id from a GlobalID string without resolving it:
|
|
104
|
+
# "gid://some-app/Account/123" => "123".
|
|
105
|
+
#
|
|
106
|
+
# Deliberately *not* `GlobalID.parse(gid)&.model_id`. Audit gids are
|
|
107
|
+
# historical and the rows are append-only, so a gid written by another
|
|
108
|
+
# app — or before this app was renamed — is a real, permanent row whose
|
|
109
|
+
# id must still be readable. Parsing it back through the locator
|
|
110
|
+
# machinery resolves against the *current* `GlobalID.app`, which is not
|
|
111
|
+
# what these rows are keyed on.
|
|
112
|
+
#
|
|
113
|
+
# This mirrors `URI::GID#set_model_components` exactly, minus the app
|
|
114
|
+
# check and the validations: drop any `?params` query, take everything
|
|
115
|
+
# after the model-name segment, split composite ids on "/", and
|
|
116
|
+
# `CGI.unescape` each part (`URI::GID.build` `CGI.escape`s them). Returns
|
|
117
|
+
# a String for a single-column primary key and an Array of Strings for a
|
|
118
|
+
# composite one, matching `GlobalID#model_id`.
|
|
119
|
+
def reference_model_id(gid)
|
|
120
|
+
return nil if gid.blank?
|
|
121
|
+
|
|
122
|
+
# "gid:" , "" , app , ModelName , <id segment(s)>
|
|
123
|
+
segment = gid.to_s.split("?", 2).first.to_s.split("/", 5)[4]
|
|
124
|
+
return nil if segment.blank?
|
|
125
|
+
|
|
126
|
+
parts = segment.split("/").reject(&:blank?).map { |part| CGI.unescape(part) }
|
|
127
|
+
return nil if parts.empty?
|
|
128
|
+
|
|
129
|
+
parts.length == 1 ? parts.first : parts
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
private
|
|
133
|
+
|
|
134
|
+
def preload_one_reference(logs, ref, only:, includes:)
|
|
135
|
+
gid_attr = :"#{ref}_gid"
|
|
136
|
+
type_attr = :"#{ref}_type"
|
|
137
|
+
allowed_names = only && Array(only).map { |klass| klass.is_a?(Module) ? klass.name : klass.to_s }
|
|
138
|
+
|
|
139
|
+
index = {}
|
|
140
|
+
unresolvable_types = []
|
|
141
|
+
|
|
142
|
+
logs.group_by { |log| log.public_send(type_attr) }.each do |type, type_logs|
|
|
143
|
+
# A blank `*_type` with a populated `*_gid` happens on historical and
|
|
144
|
+
# partially-backfilled rows. The per-row reader can still resolve
|
|
145
|
+
# those (the gid carries the model name), so mark the group
|
|
146
|
+
# unresolvable rather than memoizing nil — batching must never make a
|
|
147
|
+
# resolvable reference read back as nothing.
|
|
148
|
+
if type.blank?
|
|
149
|
+
unresolvable_types << type
|
|
150
|
+
next
|
|
151
|
+
end
|
|
152
|
+
|
|
153
|
+
# Not whitelisted: intentionally left out of the index so it memoizes
|
|
154
|
+
# nil (no query, now or later).
|
|
155
|
+
next if allowed_names && !allowed_names.include?(type)
|
|
156
|
+
|
|
157
|
+
gids = type_logs.filter_map { |log| log.public_send(gid_attr).presence }.uniq
|
|
158
|
+
next if gids.empty?
|
|
159
|
+
|
|
160
|
+
begin
|
|
161
|
+
locate_reference_records(gids, only: only, includes: includes_for(includes, type)).each do |record|
|
|
162
|
+
index[[type, normalized_record_key(record.id)]] = record
|
|
163
|
+
end
|
|
164
|
+
rescue NameError, ActiveRecord::StatementInvalid => e
|
|
165
|
+
# A historical type string that no longer constantizes, or a
|
|
166
|
+
# relation the current schema can't satisfy. Leave these rows
|
|
167
|
+
# *unmemoized* so the per-row reader behaves exactly as it did
|
|
168
|
+
# before preloading was attempted — memoizing nil here would
|
|
169
|
+
# silently rewrite behaviour on a bad `includes:`.
|
|
170
|
+
unresolvable_types << type
|
|
171
|
+
Rails.logger.warn("[StandardAudit] Could not preload #{ref} for type #{type.inspect}: #{e.class}: #{e.message}")
|
|
172
|
+
end
|
|
173
|
+
end
|
|
174
|
+
|
|
175
|
+
logs.each do |log|
|
|
176
|
+
type = log.public_send(type_attr)
|
|
177
|
+
next if unresolvable_types.include?(type)
|
|
178
|
+
|
|
179
|
+
log.write_preloaded_reference(
|
|
180
|
+
ref,
|
|
181
|
+
index[[type, reference_model_id(log.public_send(gid_attr))]]
|
|
182
|
+
)
|
|
183
|
+
end
|
|
184
|
+
end
|
|
185
|
+
|
|
186
|
+
# `ignore_missing: true` makes this a `where(id: ids)` instead of
|
|
187
|
+
# `find(ids)`, so a deleted record is simply absent from the result
|
|
188
|
+
# rather than raising — which is what lets a deleted reference memoize
|
|
189
|
+
# nil.
|
|
190
|
+
def locate_reference_records(gids, only:, includes:)
|
|
191
|
+
options = { ignore_missing: true }
|
|
192
|
+
options[:only] = only if only
|
|
193
|
+
options[:includes] = includes if includes
|
|
194
|
+
|
|
195
|
+
GlobalID::Locator.locate_many(gids, options)
|
|
196
|
+
end
|
|
197
|
+
|
|
198
|
+
# Mirrors how `GlobalID::Locator::BaseLocator#locate_many` keys its own
|
|
199
|
+
# result index, so composite primary keys line up with
|
|
200
|
+
# `reference_model_id`.
|
|
201
|
+
def normalized_record_key(id)
|
|
202
|
+
id.is_a?(Array) ? id.map(&:to_s) : id.to_s
|
|
203
|
+
end
|
|
204
|
+
|
|
205
|
+
def includes_for(includes, type)
|
|
206
|
+
return nil if includes.nil?
|
|
207
|
+
return includes unless per_type_includes?(includes)
|
|
208
|
+
|
|
209
|
+
entry = includes.find { |key, _| (key.is_a?(Module) ? key.name : key.to_s) == type }
|
|
210
|
+
entry&.last
|
|
211
|
+
end
|
|
212
|
+
|
|
213
|
+
# A Hash counts as a per-type mapping only when every key names a class.
|
|
214
|
+
# Symbol keys mean the caller passed an Active Record includes spec such
|
|
215
|
+
# as `{ account: :identifiers }`, which must be applied uniformly.
|
|
216
|
+
def per_type_includes?(includes)
|
|
217
|
+
includes.is_a?(Hash) &&
|
|
218
|
+
includes.any? &&
|
|
219
|
+
includes.keys.all? { |key| key.is_a?(String) || key.is_a?(Module) }
|
|
220
|
+
end
|
|
221
|
+
end
|
|
222
|
+
|
|
223
|
+
# Writers. `preloaded_actor = record_or_nil` is the supported way to hand a
|
|
224
|
+
# separately-resolved record to a log; `nil` means "resolved to nothing",
|
|
225
|
+
# not "clear the memo".
|
|
226
|
+
REFERENCES.each do |ref|
|
|
227
|
+
define_method(:"preloaded_#{ref}=") do |record|
|
|
228
|
+
write_preloaded_reference(ref, record)
|
|
229
|
+
end
|
|
230
|
+
|
|
231
|
+
define_method(:"#{ref}_preloaded?") do
|
|
232
|
+
reference_preloaded?(ref)
|
|
233
|
+
end
|
|
234
|
+
|
|
235
|
+
# `actor_model_id` / `target_model_id` / `scope_model_id` — the trailing
|
|
236
|
+
# gid segment, without needing the record.
|
|
237
|
+
define_method(:"#{ref}_model_id") do
|
|
238
|
+
self.class.reference_model_id(public_send(:"#{ref}_gid"))
|
|
239
|
+
end
|
|
240
|
+
end
|
|
241
|
+
|
|
242
|
+
# The memo itself. Public because `preload_references` writes through it
|
|
243
|
+
# from the class side; treat it as gem-internal — `preloaded_actor=` and
|
|
244
|
+
# `actor_preloaded?` are the supported surface.
|
|
245
|
+
def preloaded_references
|
|
246
|
+
@preloaded_references ||= {}
|
|
247
|
+
end
|
|
248
|
+
|
|
249
|
+
def reference_preloaded?(ref)
|
|
250
|
+
preloaded_references.key?(ref.to_sym)
|
|
251
|
+
end
|
|
252
|
+
|
|
253
|
+
# See `preloaded_references` — gem-internal, but public so the class-level
|
|
254
|
+
# preloader can reach it.
|
|
255
|
+
def write_preloaded_reference(ref, record)
|
|
256
|
+
preloaded_references[ref.to_sym] = record
|
|
257
|
+
end
|
|
258
|
+
|
|
259
|
+
# Drops the memo so the next read re-resolves from the (possibly changed)
|
|
260
|
+
# gid columns.
|
|
261
|
+
def reload(...)
|
|
262
|
+
@preloaded_references = nil
|
|
263
|
+
super
|
|
264
|
+
end
|
|
265
|
+
|
|
266
|
+
private
|
|
267
|
+
|
|
268
|
+
# The single-row fallback: identical to the pre-0.7.0 reader behaviour.
|
|
269
|
+
def locate_reference(ref)
|
|
270
|
+
gid = public_send(:"#{ref}_gid")
|
|
271
|
+
return nil if gid.blank?
|
|
272
|
+
|
|
273
|
+
GlobalID::Locator.locate(gid)
|
|
274
|
+
rescue ActiveRecord::RecordNotFound
|
|
275
|
+
nil
|
|
276
|
+
end
|
|
277
|
+
|
|
278
|
+
def read_reference(ref)
|
|
279
|
+
ref = ref.to_sym
|
|
280
|
+
return preloaded_references[ref] if preloaded_references.key?(ref)
|
|
281
|
+
|
|
282
|
+
locate_reference(ref)
|
|
283
|
+
end
|
|
284
|
+
|
|
285
|
+
def assign_reference(ref, record)
|
|
286
|
+
if record.nil?
|
|
287
|
+
public_send(:"#{ref}_gid=", nil)
|
|
288
|
+
public_send(:"#{ref}_type=", nil)
|
|
289
|
+
else
|
|
290
|
+
public_send(:"#{ref}_gid=", record.to_global_id.to_s)
|
|
291
|
+
public_send(:"#{ref}_type=", record.class.name)
|
|
292
|
+
end
|
|
293
|
+
|
|
294
|
+
write_preloaded_reference(ref, record)
|
|
295
|
+
record
|
|
296
|
+
end
|
|
297
|
+
end
|
|
298
|
+
end
|
data/lib/standard_audit/rspec.rb
CHANGED
|
@@ -8,9 +8,23 @@ require "standard_audit"
|
|
|
8
8
|
# - Resets the Configuration via `StandardAudit.reset_configuration!` so
|
|
9
9
|
# that mutations to `StandardAudit.config` (subscriptions, sensitive
|
|
10
10
|
# keys, async flag, custom resolvers, etc.) do not bleed across specs.
|
|
11
|
-
#
|
|
12
|
-
#
|
|
13
|
-
#
|
|
11
|
+
#
|
|
12
|
+
# IMPORTANT — declare your configuration as a baseline. The reset restores
|
|
13
|
+
# gem defaults, and the config object holds *behaviour*, not just data:
|
|
14
|
+
# `before_checksum_hooks` live there. A suite that installs this plugin
|
|
15
|
+
# without a baseline silently loses its write-time hooks after the first
|
|
16
|
+
# example, and the specs that would have caught it pass vacuously.
|
|
17
|
+
#
|
|
18
|
+
# So in `config/initializers/standard_audit.rb`, use:
|
|
19
|
+
#
|
|
20
|
+
# StandardAudit.configure(baseline: true) do |config|
|
|
21
|
+
# config.subscribe_to "myapp.**"
|
|
22
|
+
# config.before_checksum :backfill_scope
|
|
23
|
+
# end
|
|
24
|
+
#
|
|
25
|
+
# `reset_configuration!` replays that block onto the fresh Configuration,
|
|
26
|
+
# so every example starts from your app's real configuration. There is
|
|
27
|
+
# nothing to re-apply by hand in a `before` hook.
|
|
14
28
|
#
|
|
15
29
|
# The memoized `Subscriber` and `EventSubscriber` instances are *not*
|
|
16
30
|
# torn down here — they are wired up at engine boot via initializers and
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
require "set"
|
|
2
|
+
|
|
3
|
+
module StandardAudit
|
|
4
|
+
# Answers "is this redaction rule safe for MY data?" against the rows an app
|
|
5
|
+
# already has, before the rule is switched on.
|
|
6
|
+
#
|
|
7
|
+
# This matters more here than in most gems: audit rows are append-only, so a
|
|
8
|
+
# rule that swallows real audit content cannot be undone after the fact — the
|
|
9
|
+
# content is simply never written from then on. Reading the historical rows
|
|
10
|
+
# first turns the judgement call into a command.
|
|
11
|
+
#
|
|
12
|
+
# Keys are extracted **in Ruby**, not with `jsonb_object_keys`, so this works
|
|
13
|
+
# against SQLite (the dummy app), MySQL, and Postgres alike. The install
|
|
14
|
+
# template's migration uses jsonb + GIN, but the gem itself stays
|
|
15
|
+
# backend-neutral.
|
|
16
|
+
#
|
|
17
|
+
# StandardAudit::SensitiveKeysDryRun.call(sensitive_key_patterns: [/secret/i])
|
|
18
|
+
# # => #<Report rows_scanned=1204 stripped={"client_secret"=>18, ...} ...>
|
|
19
|
+
#
|
|
20
|
+
class SensitiveKeysDryRun
|
|
21
|
+
# [rows_scanned] how many audit rows were read
|
|
22
|
+
# [stripped] key path => row count, for keys the candidate rule
|
|
23
|
+
# would redact
|
|
24
|
+
# [kept] key path => row count, for keys it would keep
|
|
25
|
+
# [nested_unfiltered] key path => row count, for *nested* keys the rule
|
|
26
|
+
# matches but which are NOT redacted because
|
|
27
|
+
# `filter_nested_metadata` is off. This is the
|
|
28
|
+
# exposure `filter_nested_metadata` exists to close;
|
|
29
|
+
# empty when nested filtering is enabled.
|
|
30
|
+
Report = Struct.new(:rows_scanned, :stripped, :kept, :nested_unfiltered, :nested, keyword_init: true) do
|
|
31
|
+
def any_stripped?
|
|
32
|
+
stripped.any?
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
def to_s
|
|
36
|
+
lines = []
|
|
37
|
+
lines << "Rows scanned: #{rows_scanned}"
|
|
38
|
+
lines << "Nested filtering: #{nested ? 'on' : 'off'}"
|
|
39
|
+
lines << ""
|
|
40
|
+
|
|
41
|
+
lines << section("WOULD BE STRIPPED", stripped, "Nothing would be stripped.")
|
|
42
|
+
lines << ""
|
|
43
|
+
lines << section("KEPT", kept, "No metadata keys found.")
|
|
44
|
+
|
|
45
|
+
if nested_unfiltered.any?
|
|
46
|
+
lines << ""
|
|
47
|
+
lines << section(
|
|
48
|
+
"MATCHES BUT NOT STRIPPED (nested; set config.filter_nested_metadata = true to redact)",
|
|
49
|
+
nested_unfiltered,
|
|
50
|
+
nil
|
|
51
|
+
)
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
lines.join("\n")
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
private
|
|
58
|
+
|
|
59
|
+
def section(title, counts, empty_message)
|
|
60
|
+
out = [title, "=" * title.length]
|
|
61
|
+
|
|
62
|
+
if counts.empty?
|
|
63
|
+
out << (empty_message || "None.")
|
|
64
|
+
else
|
|
65
|
+
width = counts.keys.map(&:length).max
|
|
66
|
+
counts.sort_by { |key, count| [-count, key] }.each do |key, count|
|
|
67
|
+
out << format(" %-#{width}s %d row(s)", key, count)
|
|
68
|
+
end
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
out.join("\n")
|
|
72
|
+
end
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
class << self
|
|
76
|
+
# Every keyword defaults to the app's live configuration, so calling it
|
|
77
|
+
# with no arguments reports what the *current* config does.
|
|
78
|
+
def call(sensitive_keys: nil, sensitive_key_patterns: nil, sensitive_key_exceptions: nil,
|
|
79
|
+
nested: nil, relation: nil, batch_size: 1000)
|
|
80
|
+
new(
|
|
81
|
+
sensitive_keys: sensitive_keys,
|
|
82
|
+
sensitive_key_patterns: sensitive_key_patterns,
|
|
83
|
+
sensitive_key_exceptions: sensitive_key_exceptions,
|
|
84
|
+
nested: nested
|
|
85
|
+
).call(relation: relation, batch_size: batch_size)
|
|
86
|
+
end
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
def initialize(sensitive_keys: nil, sensitive_key_patterns: nil, sensitive_key_exceptions: nil, nested: nil)
|
|
90
|
+
live = StandardAudit.config
|
|
91
|
+
|
|
92
|
+
candidate = Configuration.new
|
|
93
|
+
candidate.sensitive_keys = sensitive_keys || live.sensitive_keys
|
|
94
|
+
candidate.sensitive_key_patterns = sensitive_key_patterns || live.sensitive_key_patterns
|
|
95
|
+
candidate.sensitive_key_exceptions = sensitive_key_exceptions || live.sensitive_key_exceptions
|
|
96
|
+
|
|
97
|
+
@nested = nested.nil? ? live.filter_nested_metadata : nested
|
|
98
|
+
@filter = MetadataFilter.new(config: candidate)
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
def call(relation: nil, batch_size: 1000)
|
|
102
|
+
relation ||= StandardAudit::AuditLog.all
|
|
103
|
+
|
|
104
|
+
rows = 0
|
|
105
|
+
stripped = Hash.new(0)
|
|
106
|
+
kept = Hash.new(0)
|
|
107
|
+
nested_unfiltered = Hash.new(0)
|
|
108
|
+
|
|
109
|
+
relation.select(:id, :metadata).find_each(batch_size: batch_size) do |log|
|
|
110
|
+
rows += 1
|
|
111
|
+
metadata = log.metadata
|
|
112
|
+
next unless metadata.respond_to?(:each_pair)
|
|
113
|
+
|
|
114
|
+
# Collect distinct paths per row first, then increment once each. A row
|
|
115
|
+
# whose `charges[]` array holds two matching hashes is ONE affected row,
|
|
116
|
+
# not two — the counts are documented as row counts.
|
|
117
|
+
row = { stripped: Set.new, kept: Set.new, nested_unfiltered: Set.new }
|
|
118
|
+
walk(metadata, nil, row, top_level: true)
|
|
119
|
+
|
|
120
|
+
row[:stripped].each { |path| stripped[path] += 1 }
|
|
121
|
+
row[:kept].each { |path| kept[path] += 1 }
|
|
122
|
+
row[:nested_unfiltered].each { |path| nested_unfiltered[path] += 1 }
|
|
123
|
+
end
|
|
124
|
+
|
|
125
|
+
Report.new(
|
|
126
|
+
rows_scanned: rows,
|
|
127
|
+
stripped: stripped,
|
|
128
|
+
kept: kept,
|
|
129
|
+
nested_unfiltered: nested_unfiltered,
|
|
130
|
+
nested: @nested
|
|
131
|
+
)
|
|
132
|
+
end
|
|
133
|
+
|
|
134
|
+
private
|
|
135
|
+
|
|
136
|
+
def walk(hash, prefix, row, top_level:)
|
|
137
|
+
hash.each_pair do |key, value|
|
|
138
|
+
name = key.to_s
|
|
139
|
+
path = prefix ? "#{prefix}.#{name}" : name
|
|
140
|
+
|
|
141
|
+
# Reserved keys are immune at every depth, and their subtree is
|
|
142
|
+
# gem-owned — never descended into. Mirrors MetadataFilter exactly, so
|
|
143
|
+
# the dry run cannot misrepresent the rule it is modelling.
|
|
144
|
+
if StandardAudit::RESERVED_METADATA_KEYS.include?(name)
|
|
145
|
+
row[:kept] << path
|
|
146
|
+
next
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
matches = @filter.filter?(name)
|
|
150
|
+
|
|
151
|
+
if matches && (top_level || @nested)
|
|
152
|
+
row[:stripped] << path
|
|
153
|
+
next
|
|
154
|
+
end
|
|
155
|
+
|
|
156
|
+
# A nested match that survives because nested filtering is off. Reported
|
|
157
|
+
# separately rather than silently counted as "kept" — this is exactly
|
|
158
|
+
# the leak `filter_nested_metadata` closes.
|
|
159
|
+
if matches
|
|
160
|
+
row[:nested_unfiltered] << path
|
|
161
|
+
else
|
|
162
|
+
row[:kept] << path
|
|
163
|
+
end
|
|
164
|
+
|
|
165
|
+
descend(value, path, row)
|
|
166
|
+
end
|
|
167
|
+
end
|
|
168
|
+
|
|
169
|
+
def descend(value, path, row)
|
|
170
|
+
if value.respond_to?(:each_pair)
|
|
171
|
+
walk(value, path, row, top_level: false)
|
|
172
|
+
elsif value.is_a?(Array)
|
|
173
|
+
value.each { |element| descend(element, "#{path}[]", row) }
|
|
174
|
+
end
|
|
175
|
+
end
|
|
176
|
+
end
|
|
177
|
+
end
|
|
@@ -79,9 +79,11 @@ module StandardAudit
|
|
|
79
79
|
raw_metadata = config.metadata_builder.call(raw_metadata)
|
|
80
80
|
end
|
|
81
81
|
|
|
82
|
-
#
|
|
83
|
-
|
|
84
|
-
|
|
82
|
+
# Redaction lives in MetadataFilter, shared with StandardAudit.record.
|
|
83
|
+
# This path previously carried its own copy that did *not* subtract
|
|
84
|
+
# RESERVED_METADATA_KEYS, so `_tags`/`_source` were strippable here and
|
|
85
|
+
# not there.
|
|
86
|
+
StandardAudit::MetadataFilter.call(raw_metadata, config: config)
|
|
85
87
|
end
|
|
86
88
|
end
|
|
87
89
|
end
|