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
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 1ab5fcec99d13f0796742d817c1dd42e45c0e8518f8967033a67194c3179ae6e
|
|
4
|
+
data.tar.gz: b0f6272a600a665615cc533b439ad2b654d54c025bd7bc2b378b5c2eac7e850d
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 1ab1f514a13f1b03501cfdf18b3c2afcf8ff214a36992edb3e00f052384826c56bf09a35c4d7c4b8f92a4f28513cd8fe5534d946622112bb27bb6f8bfd8826c7
|
|
7
|
+
data.tar.gz: 7f9fc2acdb292b06f72b2323ac0c5c780348da8d1b91e9850ae73a61eba2361fb21b3aa431888de9d0003dc2934c0ba1b2a9a060bd4bd3b2a6a1bfb71eea5680
|
data/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,63 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.7.0] - 2026-07-30
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- **Batch actor/target/scope preloading.** `AuditLog#actor` / `#target` / `#scope` resolved their GlobalID one row at a time, so every audit list N+1'd. Two consuming apps had already fixed this locally, both by reaching into private ivars (`instance_variable_set(:@preloaded_actor, …)`) because the gem exposed no setter. The gem now owns it:
|
|
15
|
+
- `AuditLog.preload_references(logs, refs: %i[actor target], only: [...], includes: {...})` resolves a page in one query per distinct stored `*_type`, built on `GlobalID::Locator.locate_many` with `ignore_missing: true`.
|
|
16
|
+
- `preloaded_actor=` / `preloaded_target=` / `preloaded_scope=` public writers, plus `actor_preloaded?` predicates.
|
|
17
|
+
- The memo is a Hash consulted with `key?`, so *preloaded-but-deleted* memoizes `nil` and reads back without a query — distinct from *not preloaded*. `actor=` / `target=` / `scope=` populate the memo (they already hold the record); `reload` clears it.
|
|
18
|
+
- `only:` is matched against the **stored type string by class name**. `GlobalID::Locator`'s own `:only` is evaluated as `gid.model_class <= klass`, which constantizes the historical type string *before* deciding whether it was permitted — so a renamed or deleted class raises `NameError` rather than being denied. Consequence: `only:` does not expand to subclasses or modules; list every concrete class. A non-whitelisted reference memoizes `nil`.
|
|
19
|
+
- `includes:` is treated as a per-type map when every key is a String or Class (`{ "Order" => [:user] }`), and as a uniform Active Record includes spec otherwise (so `{ account: :identifiers }` still works as you'd expect).
|
|
20
|
+
- A type string that no longer constantizes — or a blank `*_type` on a row that still carries a `*_gid` — is left *unmemoized*, so the per-row reader behaves exactly as it did before preloading was attempted. Preloading can never turn a resolvable reference into a permanent `nil`.
|
|
21
|
+
- `AuditLog#actor_model_id` / `#target_model_id` / `#scope_model_id` (and `AuditLog.reference_model_id(gid)`) — the model id extracted straight from the gid string, a helper three separate consumer call sites had hand-rolled. Deliberately **not** `GlobalID.parse(gid)&.model_id`: audit rows are historical and append-only, so a gid whose app segment differs from the current `GlobalID.app` is a real row that must still yield its id. Mirrors `URI::GID`'s own decoding (drops `?params`, `CGI.unescape`s each segment, returns an Array for a composite primary key) while ignoring the app name, so it agrees with `GlobalID#model_id` wherever that works and keeps working where it doesn't.
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
- **`config.before_checksum`** — registers a hook that runs on `before_create` **between `assign_uuid` and `compute_checksum`**. Definition order is execution order, so a hook may set a `CHECKSUM_FIELDS` member (back-fill `scope`, derive a column, rewrite `metadata`) and the row still passes `AuditLog.verify_chain`. Hosts previously had to register their own `before_create ..., prepend: true` to beat the gem's checksum callback — fragile ordering knowledge no host should need.
|
|
25
|
+
```ruby
|
|
26
|
+
config.before_checksum { |log| log.scope = MyApp.derive_scope(log) }
|
|
27
|
+
config.before_checksum :backfill_scope # an AuditLog instance method
|
|
28
|
+
```
|
|
29
|
+
Hooks accumulate and run in registration order. **Each is rescued individually** — a failing hook logs (and reports to `Rails.error`), is **rolled back to the attributes it started from**, and is skipped; the remaining hooks still run and the audit write never fails. The rollback is what makes "skipped" true: without it, a hook that assigns `scope_gid` and then fails a later lookup would leave a half-applied row for the following callbacks to checksum and persist. If a row is created with an explicit `checksum`, hooks still run (most derived columns are not checksummed) but the supplied digest is dropped and re-derived when a hook changed a `CHECKSUM_FIELDS` member. Hooks do not run on the batched `insert_all!` path, which never instantiates a model.
|
|
30
|
+
- **`StandardAudit.configure(baseline: true)`** — remembers the block so `reset_configuration!` replays it onto the fresh Configuration. **Required companion to the `before_checksum` hooks, not optional.** The config object holds *behaviour*, not just data, so a suite that installs `standard_audit/rspec` (whose per-example `reset_configuration!` restores gem defaults) would silently lose its write-time hooks after the first example — and the specs that would have caught it pass vacuously. The install template now uses `configure(baseline: true)`, and the `lib/standard_audit/rspec.rb` docstring no longer instructs hosts to re-apply configuration by hand. `reset_configuration!(replay_baseline: false)`, `clear_baseline_configuration!` and `baseline_configured?` round it out. A plain `configure` is unchanged and registers nothing.
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
- **`config.sensitive_key_patterns`** (Array of Regexp, always applied, default `[]`) — the supported way to catch a family of keys. Stripe's `client_secret` slipping past the exact-match `:secret` is solved by `/secret/i`.
|
|
34
|
+
|
|
35
|
+
**There is deliberately no substring matching mode**, and one should not be added. Against the current default key list, substring matching strips real audit content across the estate: `input_tokens` / `output_tokens` (live LLM cost accounting in luminality and sidekick), `token_digest` (rendered in luminality's staff audit UI), `password_reset_sent_at`, `authorization_endpoint`, even `onepassword`. Audit rows are append-only, so it cannot be undone — the content is simply never written from then on. Patterns are opt-in, per-app, and checkable in advance.
|
|
36
|
+
- **`config.sensitive_key_exceptions`** (Array of exact names or Regexps, default `[]`) — never redacted, even when `sensitive_keys` or a pattern matches. Lets an app adopt `[/token/i]` while keeping `input_tokens` / `output_tokens`.
|
|
37
|
+
- **`rake standard_audit:sensitive_keys:dry_run`** — read-only. Reports, per metadata key, what a candidate rule *would* have stripped from the rows you already have, what it would keep, and any nested matches that survive because `filter_nested_metadata` is off. Turns "is this rule safe for my app?" into a command rather than a guess, which matters precisely because the rows are append-only.
|
|
38
|
+
```bash
|
|
39
|
+
bin/rails standard_audit:sensitive_keys:dry_run # current config
|
|
40
|
+
bin/rails "standard_audit:sensitive_keys:dry_run[secret]" # candidate pattern
|
|
41
|
+
NESTED=1 bin/rails "standard_audit:sensitive_keys:dry_run[secret|token]"
|
|
42
|
+
```
|
|
43
|
+
Backed by `StandardAudit::SensitiveKeysDryRun.call(...)`, which extracts keys **in Ruby** rather than with `jsonb_object_keys` so it stays backend-neutral.
|
|
44
|
+
- `StandardAudit::MetadataFilter` — `MetadataFilter.call(metadata, config:)` filters metadata; `MetadataFilter.new.filter?(key)` answers the same question for a single key without writing a row. Matching stays **exact on the key name** (string/symbol insensitive), unchanged from 0.6.0. Anything hash-like is filtered (so `ActionController::Parameters` is redacted, not waved through because it isn't a `Hash`); `nil` passes; anything else raises `MetadataFilter::UnfilterableMetadataError` rather than writing unfiltered content to an append-only row.
|
|
45
|
+
|
|
46
|
+
### Fixed
|
|
47
|
+
|
|
48
|
+
- **Nested metadata was never redacted on either write path.** `metadata: { stripe: { client_secret: … } }` was written intact even under exact matching — a larger real leak than the top-level case. Opt in with `config.filter_nested_metadata = true` (default `false`, so 0.6.0 behaviour is preserved); redaction then descends into nested Hashes and Hashes inside Arrays. `RESERVED_METADATA_KEYS` (`_tags`, `_source`) are preserved *and their subtree is never descended into, at every depth* — they are gem-owned, and `event_subscriber.rb` sets them after building metadata.
|
|
49
|
+
- **The two write paths applied different sensitive-key filters.** `StandardAudit.record` and `StandardAudit::Subscriber#extract_metadata` each carried an independent copy of the redaction logic, and they had already diverged: the subscriber copy did not subtract `RESERVED_METADATA_KEYS`, so an app that added `:_tags` or `:_source` to `sensitive_keys` had the reserved key preserved on the `record` path and stripped on the `ActiveSupport::Notifications` path. Both now call the single `StandardAudit::MetadataFilter`, and the divergence is resolved in favour of `record`'s behaviour — reserved keys can never be filtered on either path. Parity is driven from one shared example (`spec/support/shared_examples/metadata_filtering.rb`), so a future divergence fails the suite rather than shipping.
|
|
50
|
+
|
|
51
|
+
### Notes
|
|
52
|
+
|
|
53
|
+
- `StandardAudit.batch { ... }` flushes via `insert_all!` and never instantiates a model, so none of the above runs on the batched write path — the memo is a no-op there by construction.
|
|
54
|
+
- Minor behaviour change on a single instance: `log.actor = user; user.destroy!; log.actor` now returns the (destroyed) in-memory record instead of `nil`, because the writer memoizes. Reading the row fresh (or calling `reload`) is unchanged and still returns `nil`. This matches how Active Record association writers behave.
|
|
55
|
+
|
|
56
|
+
## [0.6.0] - 2026-06-24
|
|
57
|
+
|
|
58
|
+
### Added
|
|
59
|
+
|
|
60
|
+
- `config.retention_days` now defaults from the `STANDARD_AUDIT_RETENTION_DAYS` environment variable, so a deployment can opt into a retention window without a code change. Unset/blank/zero/negative/non-numeric resolves to `nil` (infinite retention — the compliance-safe default that never auto-deletes). Host apps can still override `config.retention_days` in their initializer.
|
|
61
|
+
- `StandardAudit::Checks::Retention` — a StandardHealth-compatible (duck-typed, no hard dependency) readiness check that flags unbounded retention on **production** deployments. Register it non-critical in `config/initializers/standard_health.rb`:
|
|
62
|
+
```ruby
|
|
63
|
+
c.register_check :audit_retention, StandardAudit::Checks::Retention, critical: false
|
|
64
|
+
```
|
|
65
|
+
When `APP_ENVIRONMENT == "production"` (falling back to `Rails.env.production?` so staging is not flagged) and `retention_days` is nil, it returns `:warn`, rolling `GET /health/ready` to `:degraded` — still HTTP 200, so it surfaces the advisory without failing the probe or blocking a deploy.
|
|
66
|
+
|
|
10
67
|
## [0.5.0] - 2026-04-29
|
|
11
68
|
|
|
12
69
|
### Changed
|
data/{MIT-LICENSE → LICENSE}
RENAMED
data/README.md
CHANGED
|
@@ -164,8 +164,13 @@ organisation.scoped_audit_logs # all logs scoped to this organisation
|
|
|
164
164
|
|
|
165
165
|
## Configuration Reference
|
|
166
166
|
|
|
167
|
+
Use `configure(baseline: true)` in your initializer. It remembers the block so
|
|
168
|
+
`StandardAudit.reset_configuration!` replays it — required if your suite loads
|
|
169
|
+
`standard_audit/rspec`, because the config object holds behaviour (`before_checksum`
|
|
170
|
+
hooks) as well as data, and a per-example reset would otherwise drop it.
|
|
171
|
+
|
|
167
172
|
```ruby
|
|
168
|
-
StandardAudit.configure do |config|
|
|
173
|
+
StandardAudit.configure(baseline: true) do |config|
|
|
169
174
|
# -- Subscriptions --
|
|
170
175
|
# Subscribe to ActiveSupport::Notifications patterns.
|
|
171
176
|
# Supports wildcards.
|
|
@@ -189,9 +194,30 @@ StandardAudit.configure do |config|
|
|
|
189
194
|
config.current_session_id_resolver = -> { Current.session_id }
|
|
190
195
|
|
|
191
196
|
# -- Sensitive Data --
|
|
192
|
-
# Keys automatically stripped from metadata.
|
|
197
|
+
# Keys automatically stripped from metadata. Matching is EXACT on the key
|
|
198
|
+
# name; there is deliberately no substring mode (see below).
|
|
193
199
|
config.sensitive_keys += %i[my_custom_secret] # added to built-in defaults
|
|
194
200
|
|
|
201
|
+
# Regexps matched against every key name, in addition to the exact list.
|
|
202
|
+
# Solves e.g. Stripe's `client_secret`, which does not equal `:secret`.
|
|
203
|
+
config.sensitive_key_patterns = [/secret/i]
|
|
204
|
+
|
|
205
|
+
# Keys (exact names or Regexps) that are never redacted, so a broad pattern
|
|
206
|
+
# can keep the real audit keys it would otherwise swallow.
|
|
207
|
+
config.sensitive_key_exceptions = %i[input_tokens output_tokens]
|
|
208
|
+
|
|
209
|
+
# Descend into nested Hashes when redacting. OFF by default — without it,
|
|
210
|
+
# `metadata: { stripe: { client_secret: ... } }` is written intact.
|
|
211
|
+
config.filter_nested_metadata = true
|
|
212
|
+
|
|
213
|
+
# -- Write-time hooks --
|
|
214
|
+
# Run between the UUID assignment and the checksum computation, so a hook MAY
|
|
215
|
+
# set a checksummed column and the row still passes `verify_chain`. No
|
|
216
|
+
# `prepend: true` needed. Each hook is rescued individually and can never fail
|
|
217
|
+
# the audit write. Not run on the batched `insert_all!` path.
|
|
218
|
+
config.before_checksum { |log| log.scope = MyApp.derive_scope(log) }
|
|
219
|
+
config.before_checksum :backfill_scope # an AuditLog instance method
|
|
220
|
+
|
|
195
221
|
# -- Metadata Builder --
|
|
196
222
|
# Optional proc to transform metadata before storage.
|
|
197
223
|
config.metadata_builder = ->(metadata) { metadata.slice(:relevant_key) }
|
|
@@ -209,6 +235,8 @@ StandardAudit.configure do |config|
|
|
|
209
235
|
config.anonymizable_metadata_keys = %i[email name ip_address]
|
|
210
236
|
|
|
211
237
|
# -- Retention (schedule StandardAudit::CleanupJob to enforce) --
|
|
238
|
+
# Defaults from STANDARD_AUDIT_RETENTION_DAYS (see Retention below); set here
|
|
239
|
+
# to override per app. Leave unset for infinite retention.
|
|
212
240
|
config.retention_days = 90
|
|
213
241
|
end
|
|
214
242
|
```
|
|
@@ -339,6 +367,45 @@ File.write("export.json", JSON.pretty_generate(data))
|
|
|
339
367
|
|
|
340
368
|
Returns a hash with `subject`, `exported_at`, `total_records`, and a `records` array.
|
|
341
369
|
|
|
370
|
+
## Retention
|
|
371
|
+
|
|
372
|
+
`config.retention_days` controls how long audit logs are kept. It is only
|
|
373
|
+
enforced when you actually run cleanup (the `StandardAudit::CleanupJob` or the
|
|
374
|
+
`standard_audit:cleanup` rake task) — setting it alone deletes nothing.
|
|
375
|
+
|
|
376
|
+
It defaults from the `STANDARD_AUDIT_RETENTION_DAYS` environment variable, so a
|
|
377
|
+
deployment can opt into a retention window without a code change:
|
|
378
|
+
|
|
379
|
+
```bash
|
|
380
|
+
STANDARD_AUDIT_RETENTION_DAYS=365 # keep 365 days
|
|
381
|
+
# unset / blank / 0 / negative / non-numeric => nil => infinite retention
|
|
382
|
+
```
|
|
383
|
+
|
|
384
|
+
Infinite retention (the default) is the compliance-safe behavior: nothing is
|
|
385
|
+
ever auto-deleted. For financial/legal domains that is usually what you want;
|
|
386
|
+
enabling a finite window is a deliberate decision.
|
|
387
|
+
|
|
388
|
+
### Production retention warning (StandardHealth)
|
|
389
|
+
|
|
390
|
+
`StandardAudit::Checks::Retention` is a [StandardHealth](https://github.com/rarebit-one/standard_health)-compatible
|
|
391
|
+
check that flags unbounded retention **on production deployments** as an
|
|
392
|
+
advisory. Register it (non-critical) in `config/initializers/standard_health.rb`:
|
|
393
|
+
|
|
394
|
+
```ruby
|
|
395
|
+
StandardHealth.configure do |c|
|
|
396
|
+
c.register_check :audit_retention,
|
|
397
|
+
StandardAudit::Checks::Retention,
|
|
398
|
+
critical: false
|
|
399
|
+
end
|
|
400
|
+
```
|
|
401
|
+
|
|
402
|
+
When `APP_ENVIRONMENT == "production"` (falling back to `Rails.env.production?`
|
|
403
|
+
when that var is unset — so staging is not flagged) and `retention_days` is nil,
|
|
404
|
+
the check returns `:warn`. That rolls `GET /health/ready` up to `:degraded`,
|
|
405
|
+
which is **still HTTP 200** — it surfaces the advisory in the readiness JSON
|
|
406
|
+
without failing the probe or blocking a deploy. The check is duck-typed and has
|
|
407
|
+
no hard dependency on `standard_health`.
|
|
408
|
+
|
|
342
409
|
## Rake Tasks
|
|
343
410
|
|
|
344
411
|
```bash
|
|
@@ -382,8 +449,30 @@ t.jsonb :metadata, default: {}
|
|
|
382
449
|
|
|
383
450
|
```ruby
|
|
384
451
|
config.sensitive_keys += %i[medical_record_number] # extend the built-in defaults
|
|
452
|
+
config.sensitive_key_patterns = [/secret/i] # catch a whole family
|
|
453
|
+
config.sensitive_key_exceptions = %i[input_tokens] # ...minus the real ones
|
|
454
|
+
config.filter_nested_metadata = true # redact nested Hashes too
|
|
385
455
|
```
|
|
386
456
|
|
|
457
|
+
`sensitive_keys` matches **exactly** on the key name. There is deliberately no
|
|
458
|
+
substring mode: against the default list it would strip real audit content —
|
|
459
|
+
`input_tokens` / `output_tokens`, `token_digest`, `password_reset_sent_at`,
|
|
460
|
+
`authorization_endpoint`, `onepassword`. Audit rows are append-only, so that
|
|
461
|
+
cannot be undone. Use `sensitive_key_patterns` and check any rule against your
|
|
462
|
+
own data first:
|
|
463
|
+
|
|
464
|
+
```bash
|
|
465
|
+
bin/rails "standard_audit:sensitive_keys:dry_run[secret]" # NESTED=1 to model nesting
|
|
466
|
+
```
|
|
467
|
+
|
|
468
|
+
The dry run writes nothing. It reports per key what would be stripped, what
|
|
469
|
+
would be kept, and nested matches that survive because
|
|
470
|
+
`filter_nested_metadata` is off.
|
|
471
|
+
|
|
472
|
+
Nested metadata is **not** redacted unless `filter_nested_metadata` is enabled
|
|
473
|
+
— `metadata: { stripe: { client_secret: ... } }` passes both write paths under
|
|
474
|
+
exact matching by default.
|
|
475
|
+
|
|
387
476
|
**Performance**: For high-volume applications, enable async processing and ensure your `audit_logs` table has appropriate indexes (the install generator adds them by default). Consider partitioning by `occurred_at` for very large tables.
|
|
388
477
|
|
|
389
478
|
**Retention**: Set `retention_days` in your configuration and run `rake standard_audit:cleanup` via a scheduled job (e.g., cron or SolidQueue recurring). Archive before deleting if you need long-term storage.
|
|
@@ -2,6 +2,8 @@ require "openssl"
|
|
|
2
2
|
|
|
3
3
|
module StandardAudit
|
|
4
4
|
class AuditLog < ApplicationRecord
|
|
5
|
+
include StandardAudit::ReferencePreloading
|
|
6
|
+
|
|
5
7
|
self.table_name = "audit_logs"
|
|
6
8
|
|
|
7
9
|
CHECKSUM_FIELDS = %w[
|
|
@@ -10,7 +12,15 @@ module StandardAudit
|
|
|
10
12
|
user_agent session_id occurred_at
|
|
11
13
|
].freeze
|
|
12
14
|
|
|
15
|
+
# Callback ORDER IS THE CONTRACT here. Definition order is execution
|
|
16
|
+
# order, so registering the host hook list between assign_uuid and
|
|
17
|
+
# compute_checksum means a hook can set a CHECKSUM_FIELDS member (e.g.
|
|
18
|
+
# back-fill `scope`) and the row still verifies. Hosts previously had to
|
|
19
|
+
# register `before_create ..., prepend: true` themselves to beat
|
|
20
|
+
# compute_checksum — fragile ordering knowledge no host should need.
|
|
21
|
+
# Do not reorder these three lines.
|
|
13
22
|
before_create :assign_uuid, if: -> { id.blank? }
|
|
23
|
+
before_create :run_before_checksum_hooks
|
|
14
24
|
before_create :compute_checksum, if: -> { checksum.blank? }
|
|
15
25
|
after_create_commit :emit_created_event
|
|
16
26
|
|
|
@@ -24,61 +34,35 @@ module StandardAudit
|
|
|
24
34
|
validates :event_type, presence: true
|
|
25
35
|
validates :occurred_at, presence: true
|
|
26
36
|
|
|
27
|
-
# --
|
|
37
|
+
# -- actor / target / scope assignment via GlobalID --
|
|
38
|
+
#
|
|
39
|
+
# Reads consult the preload memo first (see ReferencePreloading), then fall
|
|
40
|
+
# back to a single `GlobalID::Locator.locate`. Writers populate the memo,
|
|
41
|
+
# since they already hold the record. If the underlying record was deleted
|
|
42
|
+
# the reader returns nil while the gid and type stay on the row.
|
|
28
43
|
|
|
29
44
|
def actor=(record)
|
|
30
|
-
|
|
31
|
-
self.actor_gid = nil
|
|
32
|
-
self.actor_type = nil
|
|
33
|
-
else
|
|
34
|
-
self.actor_gid = record.to_global_id.to_s
|
|
35
|
-
self.actor_type = record.class.name
|
|
36
|
-
end
|
|
45
|
+
assign_reference(:actor, record)
|
|
37
46
|
end
|
|
38
47
|
|
|
39
48
|
def actor
|
|
40
|
-
|
|
41
|
-
GlobalID::Locator.locate(actor_gid)
|
|
42
|
-
rescue ActiveRecord::RecordNotFound
|
|
43
|
-
nil
|
|
49
|
+
read_reference(:actor)
|
|
44
50
|
end
|
|
45
51
|
|
|
46
|
-
# -- Target assignment via GlobalID --
|
|
47
|
-
|
|
48
52
|
def target=(record)
|
|
49
|
-
|
|
50
|
-
self.target_gid = nil
|
|
51
|
-
self.target_type = nil
|
|
52
|
-
else
|
|
53
|
-
self.target_gid = record.to_global_id.to_s
|
|
54
|
-
self.target_type = record.class.name
|
|
55
|
-
end
|
|
53
|
+
assign_reference(:target, record)
|
|
56
54
|
end
|
|
57
55
|
|
|
58
56
|
def target
|
|
59
|
-
|
|
60
|
-
GlobalID::Locator.locate(target_gid)
|
|
61
|
-
rescue ActiveRecord::RecordNotFound
|
|
62
|
-
nil
|
|
57
|
+
read_reference(:target)
|
|
63
58
|
end
|
|
64
59
|
|
|
65
|
-
# -- Scope assignment via GlobalID --
|
|
66
|
-
|
|
67
60
|
def scope=(record)
|
|
68
|
-
|
|
69
|
-
self.scope_gid = nil
|
|
70
|
-
self.scope_type = nil
|
|
71
|
-
else
|
|
72
|
-
self.scope_gid = record.to_global_id.to_s
|
|
73
|
-
self.scope_type = record.class.name
|
|
74
|
-
end
|
|
61
|
+
assign_reference(:scope, record)
|
|
75
62
|
end
|
|
76
63
|
|
|
77
64
|
def scope
|
|
78
|
-
|
|
79
|
-
GlobalID::Locator.locate(scope_gid)
|
|
80
|
-
rescue ActiveRecord::RecordNotFound
|
|
81
|
-
nil
|
|
65
|
+
read_reference(:scope)
|
|
82
66
|
end
|
|
83
67
|
|
|
84
68
|
# -- Query scopes --
|
|
@@ -280,5 +264,60 @@ module StandardAudit
|
|
|
280
264
|
def assign_uuid
|
|
281
265
|
self.id = SecureRandom.uuid_v7
|
|
282
266
|
end
|
|
267
|
+
|
|
268
|
+
# Runs config.before_checksum_hooks in registration order. Each hook is
|
|
269
|
+
# rescued individually: an audit write must never fail because a host's
|
|
270
|
+
# derived-column logic did. A hook that raises is rolled back to the
|
|
271
|
+
# attributes it started from and skipped; the remaining hooks still run.
|
|
272
|
+
def run_before_checksum_hooks
|
|
273
|
+
hooks = StandardAudit.config.before_checksum_hooks
|
|
274
|
+
return if hooks.blank?
|
|
275
|
+
|
|
276
|
+
# Only relevant when a checksum was supplied explicitly (the normal path
|
|
277
|
+
# has none yet, and compute_checksum runs next).
|
|
278
|
+
checksummed_before = checksum.present? ? attributes.slice(*CHECKSUM_FIELDS) : nil
|
|
279
|
+
|
|
280
|
+
hooks.each { |hook| run_before_checksum_hook(hook) }
|
|
281
|
+
|
|
282
|
+
# A caller-supplied checksum stops describing the row the moment a hook
|
|
283
|
+
# changes a checksummed field. Dropping it lets compute_checksum
|
|
284
|
+
# re-derive one, rather than persisting a row that fails verify_chain
|
|
285
|
+
# immediately. Hooks still run for such rows, because most derived
|
|
286
|
+
# columns (actor_role and friends) are not checksummed at all.
|
|
287
|
+
self.checksum = nil if checksummed_before && attributes.slice(*CHECKSUM_FIELDS) != checksummed_before
|
|
288
|
+
end
|
|
289
|
+
|
|
290
|
+
def run_before_checksum_hook(hook)
|
|
291
|
+
snapshot = attributes.deep_dup
|
|
292
|
+
|
|
293
|
+
begin
|
|
294
|
+
case hook
|
|
295
|
+
when Symbol, String then send(hook)
|
|
296
|
+
else hook.call(self)
|
|
297
|
+
end
|
|
298
|
+
rescue StandardError => e
|
|
299
|
+
# Roll the record back to where the hook found it. Without this a hook
|
|
300
|
+
# that assigns scope_gid and then fails a later lookup leaves a
|
|
301
|
+
# half-applied row that the following callbacks happily checksum and
|
|
302
|
+
# persist — so the hook would not actually be "skipped".
|
|
303
|
+
restore_attributes_from(snapshot)
|
|
304
|
+
Rails.logger.warn("[StandardAudit] before_checksum hook failed: #{e.class}: #{e.message}")
|
|
305
|
+
Rails.error.report(e, handled: true, context: { audit_event: event_type }) if Rails.respond_to?(:error)
|
|
306
|
+
nil
|
|
307
|
+
end
|
|
308
|
+
end
|
|
309
|
+
|
|
310
|
+
def restore_attributes_from(snapshot)
|
|
311
|
+
snapshot.each do |name, value|
|
|
312
|
+
write_attribute(name, value) unless read_attribute(name) == value
|
|
313
|
+
end
|
|
314
|
+
|
|
315
|
+
# The reference memo may hold a record the hook assigned; drop it so the
|
|
316
|
+
# restored gid columns are the source of truth again.
|
|
317
|
+
@preloaded_references = nil
|
|
318
|
+
rescue StandardError => e
|
|
319
|
+
Rails.logger.warn("[StandardAudit] could not roll back a failed before_checksum hook: #{e.class}: #{e.message}")
|
|
320
|
+
nil
|
|
321
|
+
end
|
|
283
322
|
end
|
|
284
323
|
end
|
|
@@ -1,4 +1,8 @@
|
|
|
1
|
-
StandardAudit.
|
|
1
|
+
# `baseline: true` remembers this block so `StandardAudit.reset_configuration!`
|
|
2
|
+
# replays it. Required if you `require "standard_audit/rspec"` in your suite:
|
|
3
|
+
# without it, every example resets to gem defaults and loses the configuration
|
|
4
|
+
# below — including any `before_checksum` hooks, which are behaviour, not data.
|
|
5
|
+
StandardAudit.configure(baseline: true) do |config|
|
|
2
6
|
# Subscribe to ActiveSupport::Notifications / Rails.event patterns.
|
|
3
7
|
# Each gem documents its own event namespace; subscribe to whichever
|
|
4
8
|
# patterns you want audited:
|
|
@@ -27,10 +31,35 @@ StandardAudit.configure do |config|
|
|
|
27
31
|
# config.current_user_agent_resolver = -> { Current.user_agent }
|
|
28
32
|
# config.current_session_id_resolver = -> { Current.session_id }
|
|
29
33
|
|
|
30
|
-
#
|
|
31
|
-
#
|
|
32
|
-
#
|
|
34
|
+
# -- Metadata redaction ----------------------------------------------------
|
|
35
|
+
#
|
|
36
|
+
# Keys to strip from metadata. Matching is EXACT on the key name (defaults
|
|
37
|
+
# include: password, password_confirmation, token, secret, api_key,
|
|
38
|
+
# access_token, refresh_token, private_key, certificate_chain, ssn,
|
|
39
|
+
# credit_card, authorization).
|
|
33
40
|
# config.sensitive_keys += %i[my_custom_secret]
|
|
41
|
+
#
|
|
42
|
+
# Regexps matched against every key name, in addition to the exact list.
|
|
43
|
+
# This is the supported way to catch a family of keys — e.g. Stripe's
|
|
44
|
+
# `client_secret`, which does not equal the default `:secret`:
|
|
45
|
+
# config.sensitive_key_patterns = [/secret/i]
|
|
46
|
+
#
|
|
47
|
+
# There is deliberately no "substring" matching mode. Against the default
|
|
48
|
+
# key list it would strip real audit content: input_tokens/output_tokens,
|
|
49
|
+
# token_digest, password_reset_sent_at, authorization_endpoint, onepassword.
|
|
50
|
+
# Audit rows are append-only, so that cannot be undone. Check any rule
|
|
51
|
+
# against your own data first:
|
|
52
|
+
#
|
|
53
|
+
# bin/rails "standard_audit:sensitive_keys:dry_run[secret]"
|
|
54
|
+
#
|
|
55
|
+
# Keys (exact names or Regexps) that are never redacted, so a broad pattern
|
|
56
|
+
# can keep the handful of real audit keys it would otherwise swallow:
|
|
57
|
+
# config.sensitive_key_exceptions = %i[input_tokens output_tokens]
|
|
58
|
+
#
|
|
59
|
+
# Descend into nested Hashes when redacting. Off by default because it
|
|
60
|
+
# changes what gets written; `metadata: { stripe: { client_secret: ... } }`
|
|
61
|
+
# is NOT redacted unless you turn this on. Run the dry run first.
|
|
62
|
+
# config.filter_nested_metadata = true
|
|
34
63
|
|
|
35
64
|
# Run audit log creation in background job
|
|
36
65
|
# config.async = false
|
|
@@ -44,4 +73,17 @@ StandardAudit.configure do |config|
|
|
|
44
73
|
|
|
45
74
|
# Data retention (schedule StandardAudit::CleanupJob to enforce)
|
|
46
75
|
# config.retention_days = nil
|
|
76
|
+
|
|
77
|
+
# -- Write-time hooks -------------------------------------------------------
|
|
78
|
+
#
|
|
79
|
+
# Run between the UUID assignment and the checksum computation, so a hook MAY
|
|
80
|
+
# set a checksummed column (scope_gid, metadata, ...) and the row still passes
|
|
81
|
+
# `AuditLog.verify_chain`. No `prepend: true` needed.
|
|
82
|
+
#
|
|
83
|
+
# Each hook is rescued individually — a failing hook is logged and skipped and
|
|
84
|
+
# never fails the audit write. Batched writes (StandardAudit.batch, which uses
|
|
85
|
+
# insert_all!) never instantiate a model, so hooks do not run there.
|
|
86
|
+
#
|
|
87
|
+
# config.before_checksum { |log| log.scope = MyApp.derive_scope(log) }
|
|
88
|
+
# config.before_checksum :backfill_scope # an AuditLog instance method
|
|
47
89
|
end
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
module StandardAudit
|
|
2
|
+
module Checks
|
|
3
|
+
# A StandardHealth-compatible readiness check that warns when audit_logs
|
|
4
|
+
# retention is unbounded on a production deployment.
|
|
5
|
+
#
|
|
6
|
+
# It is intentionally duck-typed (no hard dependency on standard_health):
|
|
7
|
+
# it exposes the `#initialize(name:, critical:)` + `#run` contract the
|
|
8
|
+
# StandardHealth aggregator calls, so it loads even where standard_health
|
|
9
|
+
# is absent.
|
|
10
|
+
#
|
|
11
|
+
# Register it (NON-critical) in config/initializers/standard_health.rb:
|
|
12
|
+
#
|
|
13
|
+
# c.register_check :audit_retention,
|
|
14
|
+
# StandardAudit::Checks::Retention,
|
|
15
|
+
# critical: false
|
|
16
|
+
#
|
|
17
|
+
# A :warn result rolls /health/ready up to :degraded, which is still
|
|
18
|
+
# HTTP 200 — it surfaces the advisory in the readiness JSON WITHOUT failing
|
|
19
|
+
# the probe or blocking a deploy. Only a *critical* check failure returns
|
|
20
|
+
# 503, and this check is never critical.
|
|
21
|
+
#
|
|
22
|
+
# "Production" is ENV["APP_ENVIRONMENT"] == "production" when that var is
|
|
23
|
+
# set (so staging — which also runs RAILS_ENV=production — is not flagged);
|
|
24
|
+
# otherwise it falls back to Rails.env.production?.
|
|
25
|
+
class Retention
|
|
26
|
+
def initialize(name: :audit_retention, critical: false)
|
|
27
|
+
@name = name
|
|
28
|
+
@critical = critical
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
def run
|
|
32
|
+
unless production?
|
|
33
|
+
return { status: :ok, detail: "retention advisory only runs on production deployments" }
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
days = StandardAudit.config.retention_days
|
|
37
|
+
return { status: :ok, retention_days: days } if days
|
|
38
|
+
|
|
39
|
+
{
|
|
40
|
+
status: :warn,
|
|
41
|
+
message: "audit_logs retention is unbounded on production. Set " \
|
|
42
|
+
"STANDARD_AUDIT_RETENTION_DAYS (or config.retention_days) and schedule " \
|
|
43
|
+
"StandardAudit::CleanupJob, or treat indefinite retention as a deliberate " \
|
|
44
|
+
"compliance decision."
|
|
45
|
+
}
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
private
|
|
49
|
+
|
|
50
|
+
def production?
|
|
51
|
+
app_env = ENV["APP_ENVIRONMENT"].to_s
|
|
52
|
+
return app_env == "production" unless app_env.empty?
|
|
53
|
+
|
|
54
|
+
defined?(Rails) && Rails.respond_to?(:env) && Rails.env.production?
|
|
55
|
+
end
|
|
56
|
+
end
|
|
57
|
+
end
|
|
58
|
+
end
|
|
@@ -5,7 +5,9 @@ module StandardAudit
|
|
|
5
5
|
:current_actor_resolver, :current_request_id_resolver,
|
|
6
6
|
:current_ip_address_resolver, :current_user_agent_resolver,
|
|
7
7
|
:current_session_id_resolver,
|
|
8
|
-
:sensitive_keys, :
|
|
8
|
+
:sensitive_keys, :sensitive_key_patterns,
|
|
9
|
+
:sensitive_key_exceptions, :filter_nested_metadata,
|
|
10
|
+
:metadata_builder, :before_checksum_hooks,
|
|
9
11
|
:anonymizable_metadata_keys, :retention_days
|
|
10
12
|
|
|
11
13
|
def initialize
|
|
@@ -43,9 +45,85 @@ module StandardAudit
|
|
|
43
45
|
private_key certificate_chain
|
|
44
46
|
ssn credit_card authorization
|
|
45
47
|
]
|
|
48
|
+
# Regexps matched against every metadata key name, in addition to the
|
|
49
|
+
# exact-match `sensitive_keys` list. This is the supported way to catch a
|
|
50
|
+
# family of keys: `/secret/i` redacts `client_secret`, `webhook_secret`,
|
|
51
|
+
# and `secret` alike.
|
|
52
|
+
#
|
|
53
|
+
# There is deliberately NO substring *mode* for `sensitive_keys` — see
|
|
54
|
+
# the note in MetadataFilter. Patterns are opt-in and per-app, which is
|
|
55
|
+
# the only safe shape for a rule applied to append-only rows.
|
|
56
|
+
@sensitive_key_patterns = []
|
|
57
|
+
|
|
58
|
+
# Key names (String/Symbol, exact) or Regexps that are never redacted,
|
|
59
|
+
# even when `sensitive_keys` or `sensitive_key_patterns` matches. Lets an
|
|
60
|
+
# app adopt a broad pattern while keeping the handful of real audit keys
|
|
61
|
+
# it would otherwise swallow, e.g.
|
|
62
|
+
# `sensitive_key_patterns = [/token/i]` with
|
|
63
|
+
# `sensitive_key_exceptions = %i[input_tokens output_tokens]`.
|
|
64
|
+
@sensitive_key_exceptions = []
|
|
65
|
+
|
|
66
|
+
# When true, redaction descends into nested Hashes (and Hashes inside
|
|
67
|
+
# Arrays), so `metadata: { stripe: { client_secret: … } }` is caught.
|
|
68
|
+
# Defaults to false: it changes what gets written, and audit rows are
|
|
69
|
+
# append-only. Reserved keys are never descended into.
|
|
70
|
+
@filter_nested_metadata = false
|
|
71
|
+
|
|
46
72
|
@metadata_builder = nil
|
|
73
|
+
|
|
74
|
+
# Callables (or Symbols naming an AuditLog instance method) run on
|
|
75
|
+
# `before_create` AFTER the UUID is assigned and BEFORE the checksum is
|
|
76
|
+
# computed. See Configuration#before_checksum.
|
|
77
|
+
@before_checksum_hooks = []
|
|
78
|
+
|
|
47
79
|
@anonymizable_metadata_keys = %i[email name ip_address]
|
|
48
|
-
|
|
80
|
+
|
|
81
|
+
# Retention defaults from ENV so it can be set per-environment without a
|
|
82
|
+
# code change. Unset/blank/non-positive => nil (infinite retention, the
|
|
83
|
+
# compliance-safe default that never auto-deletes). A host app can still
|
|
84
|
+
# override with `config.retention_days = N` in its initializer.
|
|
85
|
+
@retention_days = self.class.retention_days_from_env
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
# Parses STANDARD_AUDIT_RETENTION_DAYS into a positive Integer, or nil when
|
|
89
|
+
# unset/blank/zero/negative/non-numeric (=> infinite retention).
|
|
90
|
+
def self.retention_days_from_env
|
|
91
|
+
raw = ENV["STANDARD_AUDIT_RETENTION_DAYS"]
|
|
92
|
+
return nil if raw.nil? || raw.strip.empty?
|
|
93
|
+
|
|
94
|
+
days = Integer(raw, exception: false)
|
|
95
|
+
days&.positive? ? days : nil
|
|
96
|
+
end
|
|
97
|
+
|
|
98
|
+
# Registers a hook to run between `assign_uuid` and `compute_checksum` on
|
|
99
|
+
# every audit write that instantiates a model.
|
|
100
|
+
#
|
|
101
|
+
# config.before_checksum { |log| log.scope = derive_scope(log) }
|
|
102
|
+
# config.before_checksum :backfill_organization_scope
|
|
103
|
+
#
|
|
104
|
+
# A hook may set a `CHECKSUM_FIELDS` member (`scope_gid`, `metadata`, …) and
|
|
105
|
+
# the row will still verify, because the checksum is computed afterwards.
|
|
106
|
+
# That is the whole point: before this existed, hosts had to register their
|
|
107
|
+
# own `before_create ..., prepend: true` to beat the gem's checksum
|
|
108
|
+
# callback, which is fragile ordering knowledge no host should need.
|
|
109
|
+
#
|
|
110
|
+
# Hooks accumulate and run in registration order. Each is rescued
|
|
111
|
+
# individually — a failing hook logs and is skipped; it never fails the
|
|
112
|
+
# audit write.
|
|
113
|
+
#
|
|
114
|
+
# A Symbol/String is sent to the AuditLog instance (use this for methods
|
|
115
|
+
# supplied by a concern mixed into the model). A callable is passed the
|
|
116
|
+
# instance.
|
|
117
|
+
#
|
|
118
|
+
# NOTE: batched writes (`StandardAudit.batch { … }` → `insert_all!`) never
|
|
119
|
+
# instantiate a model, so hooks do not run there. A batched writer that
|
|
120
|
+
# needs a derived column has to set it on the buffered attrs.
|
|
121
|
+
def before_checksum(hook = nil, &block)
|
|
122
|
+
hook ||= block
|
|
123
|
+
raise ArgumentError, "before_checksum needs a callable, a Symbol, or a block" if hook.nil?
|
|
124
|
+
|
|
125
|
+
@before_checksum_hooks << hook
|
|
126
|
+
hook
|
|
49
127
|
end
|
|
50
128
|
|
|
51
129
|
def subscribe_to(pattern)
|