rubocop-dev_doc 0.17.0 → 0.19.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.
Files changed (48) hide show
  1. checksums.yaml +4 -4
  2. data/config/default.yml +461 -62
  3. data/config/obsoletion.yml +7 -3
  4. data/lib/dev_doc/i18n/pseudo_locale.rb +1 -1
  5. data/lib/dev_doc/i18n/tasks.rb +68 -0
  6. data/lib/dev_doc/railtie.rb +19 -0
  7. data/lib/dev_doc/test/lints/cross_tenant_canary_check.rb +1 -1
  8. data/lib/dev_doc/test/lints/cross_tenant_canary_sweep.rb +8 -3
  9. data/lib/dev_doc/test/lints/http_driven_controller_tests.rb +4 -0
  10. data/lib/dev_doc/test/lints/no_file_excludes.rb +1 -1
  11. data/lib/dev_doc/test/pseudo_i18n_crawler.rb +9 -0
  12. data/lib/rubocop/cop/dev_doc/auth/adjacent_justification.rb +44 -7
  13. data/lib/rubocop/cop/dev_doc/auth/load_resource_current_user_guard.rb +2 -2
  14. data/lib/rubocop/cop/dev_doc/auth/login_only_policy_justification.rb +1 -1
  15. data/lib/rubocop/cop/dev_doc/auth/unscoped_find_justification.rb +2 -2
  16. data/lib/rubocop/cop/dev_doc/bundler/conflicting_gem.rb +74 -0
  17. data/lib/rubocop/cop/dev_doc/exception_class_list.rb +32 -0
  18. data/lib/rubocop/cop/dev_doc/i18n/hardcoded_text.rb +243 -0
  19. data/lib/rubocop/cop/dev_doc/i18n/localizable_props.rb +69 -19
  20. data/lib/rubocop/cop/dev_doc/i18n/require_translation.rb +13 -17
  21. data/lib/rubocop/cop/dev_doc/i18n/text_shape.rb +94 -0
  22. data/lib/rubocop/cop/dev_doc/i18n/translation_key_prefix.rb +1 -1
  23. data/lib/rubocop/cop/dev_doc/migration/legacy_migration.rb +26 -0
  24. data/lib/rubocop/cop/dev_doc/migration/redundant_reference_index.rb +5 -15
  25. data/lib/rubocop/cop/dev_doc/migration/require_reference_index.rb +115 -0
  26. data/lib/rubocop/cop/dev_doc/rails/avoid_bypassing_validation.rb +81 -26
  27. data/lib/rubocop/cop/dev_doc/rails/avoid_lifecycle_method_override.rb +1 -1
  28. data/lib/rubocop/cop/dev_doc/rails/no_error_message_comparison.rb +178 -0
  29. data/lib/rubocop/cop/dev_doc/rails/no_errors_add_in_controller.rb +177 -0
  30. data/lib/rubocop/cop/dev_doc/rails/no_form_param_lookup_in_controller.rb +236 -0
  31. data/lib/rubocop/cop/dev_doc/style/avoid_kernel_array.rb +103 -0
  32. data/lib/rubocop/cop/dev_doc/style/in_memory_association_find.rb +162 -0
  33. data/lib/rubocop/cop/dev_doc/style/no_silent_rescue.rb +279 -0
  34. data/lib/rubocop/cop/dev_doc/style/no_unscoped_method_definitions.rb +1 -1
  35. data/lib/rubocop/cop/dev_doc/style/prefer_allowlist_symbol_param.rb +193 -0
  36. data/lib/rubocop/cop/dev_doc/style/rescue_justification.rb +330 -0
  37. data/lib/rubocop/cop/dev_doc/style/use_g_log.rb +133 -0
  38. data/lib/rubocop/cop/dev_doc/test/justification_covers.rb +216 -0
  39. data/lib/rubocop/cop/dev_doc/test/justification_header.rb +86 -5
  40. data/lib/rubocop/cop/dev_doc/test/prefer_find_sole_by.rb +146 -0
  41. data/lib/rubocop/cop/dev_doc/test/require_job_invocation_in_job_tests.rb +154 -0
  42. data/lib/rubocop/cop/dev_doc/test/require_unit_test_justification.rb +5 -24
  43. data/lib/rubocop/cop/dev_doc/test/test_file_placement.rb +30 -2
  44. data/lib/rubocop/cop/dev_doc/test/test_name_special_characters.rb +108 -0
  45. data/lib/rubocop/cop/dev_doc/view/prefer_prop_over_name.rb +11 -1
  46. data/lib/rubocop/dev_doc/version.rb +1 -1
  47. metadata +24 -4
  48. data/lib/rubocop/cop/dev_doc/i18n/report_text.rb +0 -76
@@ -0,0 +1,193 @@
1
+ module RuboCop
2
+ module Cop
3
+ module DevDoc
4
+ module Style
5
+ # Flag a hand-rolled allow-list lookup — a `find`/`detect` block that
6
+ # compares each entry of a fixed list (bare or `.to_s`'d) against a
7
+ # request param — where the boundary helper already owns the decision.
8
+ #
9
+ # ## Rationale
10
+ # `glib_allowlist_symbol_param(value, ALLOWED, default:)` exists so the
11
+ # missing/junk/blank-value decision lives in one reviewed place. The
12
+ # hand-rolled `LIST.find { |entry| entry.to_s == params[:x].to_s }`
13
+ # re-derives the helper's internals at the call site: the
14
+ # degrade-to-default policy, the nil/blank fallthrough and the
15
+ # string-space (symbol-DoS-safe) comparison all get re-implemented by
16
+ # hand, and the next reader cannot tell an intentional degrade from an
17
+ # oversight. A real instance of exactly this shape slipped through
18
+ # review carrying a paragraph of commentary explaining what the
19
+ # helper's name already encodes.
20
+ #
21
+ # ## Relationship with the boundary cop pair
22
+ # Third of the trio over the same boundary doctrine.
23
+ # `DevDoc/Style/StringSymbolComparison` polices comparing without
24
+ # converting (always-false `==` against a symbol literal);
25
+ # `DevDoc/Style/AvoidSymbolizingBoundaryInput` polices converting
26
+ # without validating (`.to_sym` on params). This cop polices the third
27
+ # shape: validating by hand instead of through the shared helper. All
28
+ # three share the same sanctioned exit.
29
+ #
30
+ # ## Exception — the swap is a behavior change on mutating requests
31
+ # On GET/HEAD the helper degrades unrecognised values to `default`,
32
+ # exactly like the hand-roll. On a mutating request it raises
33
+ # `UnrecognizedValue` on a present-but-unrecognised value — the
34
+ # intended doctrine for values the UI wrote (a mismatch means a
35
+ # forgotten allow-list entry or a broken client and must surface).
36
+ # Where a silent degrade is deliberate — an endpoint anyone can
37
+ # POST to, where junk values are expected traffic — pass the
38
+ # helper's `raise_on_unrecognized: false` (glib-web 7.0.2+):
39
+ # unrecognised values then degrade to `default` on every method,
40
+ # matching the hand-roll's degrade-vs-raise behavior. (The return
41
+ # type follows the remedy's own rule either way: the helper always
42
+ # symbolizes the matched entry, including entries from string
43
+ # lists.)
44
+ #
45
+ # ## Sources detected
46
+ # - `params[…]`, `params.dig(…)`, `params.fetch(…)`, `params.require(…)`
47
+ # - `request.headers[…]`
48
+ #
49
+ # `ENV[…]` is deliberately excluded, as in
50
+ # `DevDoc/Style/AvoidSymbolizingBoundaryInput`: operator-controlled,
51
+ # not attacker-reachable, and boot-time config code has no controller
52
+ # helper to call.
53
+ #
54
+ # NOTE: only the direct `find`/`detect` block form is detected, and
55
+ # only over a developer-controlled list: the body must be a single
56
+ # `==` comparison (parentheses around it are fine; multi-statement
57
+ # bodies, modifier-`if`/`rescue` bodies and `!=` are not), and the
58
+ # iterated collection must not itself be boundary-sourced —
59
+ # `params[:ids].find { … }` is a lookup inside client data, not an
60
+ # allow-list, and the helper's `.to_sym` must never run over client
61
+ # entries. A `Hash#find` over pairs (`PRESETS.find { |key, _config| … }`)
62
+ # fires too; its remedy passes `.keys` and returns the key, not the
63
+ # `[key, value]` pair. Membership predicates over the same comparison
64
+ # (`any?`, `include?`), the numbered-block and `it` spellings (`_1`,
65
+ # Ruby 3.4's `it`), a param already flowed into a local or helper
66
+ # (`report_params[:x]`), a `params.permit(…)[]` read (not a detected
67
+ # source, as in the sibling cops), and a laundered list receiver
68
+ # (`params[:ids].map(&:to_i).find { … }`) are beyond static reach —
69
+ # review catches those.
70
+ #
71
+ # @example
72
+ # # bad
73
+ # preset = PRESETS.keys.find { |key| key.to_s == params[:preset].to_s }
74
+ # mode = MODES.find { |mode| params[:mode].to_s == mode.to_s }
75
+ # status = STATUSES.detect { |status| status == params[:status] }
76
+ #
77
+ # # good
78
+ # preset = glib_allowlist_symbol_param(params[:preset], PRESETS.keys, default: DEFAULT_PRESET)
79
+ # mode = glib_allowlist_symbol_param(params[:mode], MODES, default: :active)
80
+ # status = glib_allowlist_symbol_param(params[:status], STATUSES, default: :draft)
81
+ class PreferAllowlistSymbolParam < Base
82
+ MSG = 'Hand-rolled allow-list lookup against `%<source>s`; use ' \
83
+ '`glib_allowlist_symbol_param(value, ALLOWED, default:)` instead.'.freeze
84
+
85
+ # String-preserving transforms that may sit between the boundary
86
+ # read and the comparison — same laundering-hop doctrine as
87
+ # AvoidSymbolizingBoundaryInput.
88
+ TRANSFORM_HOPS = %i[presence to_s strip downcase upcase squish].freeze
89
+
90
+ def_node_matcher :params_access?, <<~PATTERN
91
+ (send (send nil? :params) {:[] :dig :fetch :require} ...)
92
+ PATTERN
93
+
94
+ def_node_matcher :request_headers_access?, <<~PATTERN
95
+ (send (send _ :headers) :[] _)
96
+ PATTERN
97
+
98
+ def on_block(node)
99
+ return unless %i[find detect].include?(node.send_node.method_name)
100
+ # A boundary-sourced list is a lookup inside client data, not an
101
+ # allow-list (see NOTE): the helper's `.to_sym` must never run
102
+ # over client-controlled entries.
103
+ return if boundary_source_in(node.send_node.receiver)
104
+
105
+ source = boundary_lookup(node)
106
+ return unless source
107
+
108
+ add_offense(node, message: format(MSG, source: source.source))
109
+ end
110
+
111
+ private
112
+
113
+ # The boundary access in the block's `==` comparison, whichever side
114
+ # holds it; nil when the body is not a single comparison or neither
115
+ # side reads the boundary.
116
+ def boundary_lookup(block)
117
+ comparison = block_comparison(block.body)
118
+ return unless comparison
119
+
120
+ names = block_arg_names(block)
121
+ lookup_source(comparison.receiver, comparison.first_argument, names) ||
122
+ lookup_source(comparison.first_argument, comparison.receiver, names)
123
+ end
124
+
125
+ # The block's `==` comparison, or nil for any other body shape.
126
+ # Parentheses mint a single-child `begin` around the comparison;
127
+ # those are unwrapped so `(entry.to_s == params[:x].to_s)` still
128
+ # matches, while multi-statement bodies keep their multi-child
129
+ # begin and fall out here.
130
+ def block_comparison(body)
131
+ body = body.children.first while single_child_begin?(body)
132
+ body if body&.send_type? && body.method?(:==)
133
+ end
134
+
135
+ def single_child_begin?(node)
136
+ node&.begin_type? && node.children.one?
137
+ end
138
+
139
+ # The compared block arguments (`|key|`); destructured arguments
140
+ # have no single name and contribute none.
141
+ def block_arg_names(block)
142
+ block.arguments.filter_map { |arg| arg.name if arg.arg_type? }
143
+ end
144
+
145
+ # The boundary access behind `other_operand`, when the OTHER side is
146
+ # the allow-list entry. Returns nil otherwise.
147
+ def lookup_source(entry_operand, other_operand, names)
148
+ return unless entry_operand?(entry_operand, names)
149
+
150
+ boundary_source_in(other_operand)
151
+ end
152
+
153
+ # The allow-list entry side: a bare block argument (`|status|`) or
154
+ # its string form (`|key| key.to_s`, `key&.to_s`). Anything richer —
155
+ # an attribute of the iterated record (`u.email`) or another method
156
+ # call on it — is a lookup-by-value, not an allow-list, and is left
157
+ # alone.
158
+ def entry_operand?(operand, names)
159
+ return true if operand.lvar_type? && names.include?(operand.name)
160
+
161
+ to_s_on_entry?(operand) && names.include?(operand.receiver.name)
162
+ end
163
+
164
+ # The entry's own `.to_s` — the helper's own comparison shape,
165
+ # whatever the list holds.
166
+ def to_s_on_entry?(operand)
167
+ (operand.send_type? || operand.csend_type?) && operand.method?(:to_s) &&
168
+ operand.receiver&.lvar_type?
169
+ end
170
+
171
+ # The boundary source at the bottom of the receiver chain, walking
172
+ # through laundering transforms (mirrors
173
+ # AvoidSymbolizingBoundaryInput#boundary_source_in). Returns nil for
174
+ # anything else (locals, ivars, helper-method results) so those
175
+ # don't false-positive.
176
+ def boundary_source_in(node)
177
+ while node
178
+ return node if boundary_source?(node)
179
+ return nil unless node.send_type? || node.csend_type?
180
+ return nil unless TRANSFORM_HOPS.include?(node.method_name)
181
+
182
+ node = node.receiver
183
+ end
184
+ end
185
+
186
+ def boundary_source?(node)
187
+ params_access?(node) || request_headers_access?(node)
188
+ end
189
+ end
190
+ end
191
+ end
192
+ end
193
+ end
@@ -0,0 +1,330 @@
1
+ module RuboCop
2
+ module Cop
3
+ module DevDoc
4
+ module Style
5
+ # Flag a block-form `rescue` clause that has no reason to exist on
6
+ # record: it rescues something other than a failure no validator can
7
+ # prevent, does not propagate, and carries no
8
+ # `rescue-reason: <category>: <why>` comment.
9
+ #
10
+ # ## Rationale
11
+ # A rescue is a claim that the operation can still fail HERE. On data
12
+ # a validator already accepted, that claim contradicts the validator:
13
+ # either the validator has a gap (close it) or the rescue is dead
14
+ # (drop it). Leaving the rescue in place is worse than either. A
15
+ # clause that turns an exception into a plausible value
16
+ # (`rescue StandardError; false`) converts a bug in our own code, or
17
+ # a value the validator should have refused, into a wrong answer
18
+ # rather than no answer: the condition "did not match", the record
19
+ # "was not found", and the symptom surfaces weeks later far from the
20
+ # cause. Reporting the exception on the way (which
21
+ # `DevDoc/Style/NoSilentRescue` asks for) does not fix this; a log
22
+ # line nobody is paged for still hides that the answer was wrong.
23
+ #
24
+ # Three kinds of clause are legitimate without a stated reason:
25
+ #
26
+ # - **Concurrency verdicts** (`ActiveRecord::RecordNotUnique`,
27
+ # `Deadlocked`, `LockWaitTimeout`, `StaleObjectError`,
28
+ # `SerializationFailure`). Validation is point-in-time; under a
29
+ # race the database constraint is the only check that holds, and
30
+ # rescuing its verdict is how the code learns it lost.
31
+ # - **I/O to another system** (`Errno::`, `Net::`, `Timeout::Error`,
32
+ # `IOError`, `EOFError`, `SocketError`, `OpenSSL::SSL::SSLError`,
33
+ # lost database connections). Nothing of ours validated the other
34
+ # side.
35
+ # - **Propagation.** A body that re-raises, raises a domain error in
36
+ # translation (`rescue JSON::ParserError => e; raise ApiError,
37
+ # ...`) or `throw`s is error translation at a boundary, not
38
+ # distrust of a value.
39
+ #
40
+ # Everything else states its reason, including parse errors of
41
+ # untrusted input: the `boundary-parse` category is one line, and
42
+ # writing it is the author asserting that the input is external and
43
+ # the parse is the validation.
44
+ #
45
+ # ## Matching is fail-closed
46
+ # RuboCop has no type information, so the cop matches each rescued
47
+ # constant AS WRITTEN (leading `::` ignored). Anything it does not
48
+ # recognise needs a marker: a bare `rescue`, `rescue => e`,
49
+ # `StandardError`, `ArgumentError`, `ActiveRecord::RecordInvalid`,
50
+ # `JSON::ParserError`, a splat (`rescue *RETRYABLE`), a method call
51
+ # in class position, and a project's own error class written
52
+ # unqualified (`rescue TimeoutError` inside a namespace that defines
53
+ # one). A clause rescuing several classes passes only when EVERY
54
+ # one is allowed. This is what keeps the cop generic: a new gem's
55
+ # error class or a new project exception never slips through by
56
+ # resembling a listed one. It either goes on the project's
57
+ # `ExpectedErrorClasses` (one reviewed config line, for a class that
58
+ # really is external I/O — an HTTP client's or a payment API's
59
+ # error root) or each rescue of it states a reason.
60
+ #
61
+ # ## What an offense means
62
+ # An offense does NOT assert the rescue is wrong; it asserts nobody
63
+ # has said why it is right. The remedies, in order of preference:
64
+ #
65
+ # 1. Drop the rescue when a validator upstream already guarantees
66
+ # the operation succeeds, or close the validator's gap so that it
67
+ # does.
68
+ # 2. Narrow it to the external classes when the failure really is
69
+ # I/O (`rescue Net::OpenTimeout, SocketError` instead of
70
+ # `rescue StandardError` around an HTTP call).
71
+ # 3. State the reason. The category is one of a closed set, so a
72
+ # reviewer can sort and audit every rescue of a codebase in one
73
+ # grep; the free text after it is what the reviewer judges.
74
+ #
75
+ # ❌ an evaluator bug becomes "the condition did not match"
76
+ # def matches?(member)
77
+ # evaluate(member)
78
+ # rescue StandardError => e
79
+ # GLog.error(e)
80
+ # false
81
+ # end
82
+ #
83
+ # ✔️ no rescue — the seed validator rejects what cannot evaluate
84
+ # def matches?(member)
85
+ # evaluate(member)
86
+ # end
87
+ #
88
+ # ✔️ one failing unit must not abort the sweep, reason stated
89
+ # members.find_each do |member|
90
+ # deliver(member)
91
+ # rescue StandardError => e # rescue-reason: bulkhead: one member's failure must not stop the batch
92
+ # GLog.error(e)
93
+ # end
94
+ #
95
+ # ## Categories
96
+ # `bulkhead` (one failure unit of a batch or async sweep must not
97
+ # abort the rest; one per unit of work, reported), `side-effect` (a
98
+ # secondary effect that must not fail the primary action it rides
99
+ # on), `degrade` (a user-facing path that degrades to a fallback and
100
+ # reports), `boundary-parse` (untrusted external input parsed here;
101
+ # the parse is the validation), `surface` (a non-bang wrapper
102
+ # turning a bang method's exception into the contract's failure
103
+ # channel, false + errors), `delivery` (a controller rendering a
104
+ # domain error raised below it). `delivery` is the one category with
105
+ # a structural signature, so the cop checks it: it is accepted only
106
+ # in files under `app/controllers/`. The other five have no static
107
+ # signature; their text is what the reviewer judges.
108
+ #
109
+ # ## Relationship with `DevDoc/Style/NoSilentRescue`
110
+ # Orthogonal. NoSilentRescue judges the BODY (does the failure leave
111
+ # a trace?); this cop judges the CLAUSE (should it exist?). A site
112
+ # can pass either and fail the other: a reported
113
+ # `rescue StandardError` passes NoSilentRescue and needs a reason
114
+ # here; a `rescue ActiveRecord::RecordNotUnique; nil` passes both
115
+ # (NoSilentRescue's `ExpectedOutcomeClasses`). The two markers are
116
+ # different on purpose and a site may carry both — a bulkhead that
117
+ # also degrades silently states each.
118
+ #
119
+ # Modifier rescues (`value rescue fallback`) are out of scope, as in
120
+ # NoSilentRescue: `Style/RescueModifier` flags every one on form
121
+ # alone, and the modifier form has no room for a marker.
122
+ #
123
+ # ## Configuration
124
+ # `JustificationMarker` (default: `rescue-reason:`) — accepted in
125
+ # three placements: trailing on the `rescue` line, in the contiguous
126
+ # block of comment-only lines ending directly above it, or in the
127
+ # body's leading comment block directly below it. Unlike
128
+ # NoSilentRescue, a comment trailing a code line above does not
129
+ # count: in a multi-clause rescue that line is the previous clause's
130
+ # body, and its reason is that clause's. The category is the first
131
+ # word after the marker, case-insensitive, ending at whitespace or
132
+ # `:`, with a trailing `-` stripped. Every marker in every placement
133
+ # is read, and one naming a valid category is enough.
134
+ #
135
+ # `ExpectedErrorClasses` — the race and I/O classes above. An entry
136
+ # ending in `::` matches a namespace (`Errno::`). Setting the key in
137
+ # a project REPLACES the default list (RuboCop's normal semantics
138
+ # for list config): copy the default from the gem's
139
+ # `config/default.yml` and append the project's external-I/O roots,
140
+ # e.g. `Stripe::StripeError`, `OAuth2::Error`, `Google::Cloud::Error`,
141
+ # `Google::Apis::ClientError`, `RestClient::`,
142
+ # `Twilio::REST::TwilioError`. `ActiveRecord::StatementInvalid` and
143
+ # `PG::Error` are deliberately absent: they carry SQL bugs as well
144
+ # as connectivity.
145
+ #
146
+ # `Categories` — `name: { Meaning: ..., Path: ... }`. `Meaning` is
147
+ # rendered into the offense message; `Path`, when present, restricts
148
+ # the category to files whose path contains it.
149
+ #
150
+ # NOTE: The propagation walk is syntactic and shared with
151
+ # NoSilentRescue: a `raise` on any branch of the body exempts the
152
+ # clause, and so does any call named `raise`/`fail`/`throw` whatever
153
+ # its receiver. One marker in an empty clause's body also sits
154
+ # directly above the next clause's `rescue` and justifies both.
155
+ # Nested bulkheads (a per-trigger rescue around a per-entity rescue
156
+ # around an evaluator rescue) span methods and are not
157
+ # detected; the markers make them a one-glance review finding
158
+ # instead — two `bulkhead` markers on one call chain. Only `app/` and
159
+ # `lib/` are inspected.
160
+ #
161
+ # @example
162
+ # # bad — StandardError around our own code, no reason
163
+ # begin
164
+ # evaluate(tree)
165
+ # rescue StandardError
166
+ # false
167
+ # end
168
+ #
169
+ # # good — a lost race is an expected verdict
170
+ # begin
171
+ # Run.create!(member: member)
172
+ # rescue ActiveRecord::RecordNotUnique
173
+ # nil
174
+ # end
175
+ #
176
+ # # good — error translation at a boundary
177
+ # begin
178
+ # JSON.parse(body)
179
+ # rescue JSON::ParserError => e
180
+ # raise ApiError, e.message
181
+ # end
182
+ #
183
+ # # good — reason stated
184
+ # begin
185
+ # JSON.parse(params[:payload])
186
+ # rescue JSON::ParserError # rescue-reason: boundary-parse: webhook body from the vendor
187
+ # head :bad_request
188
+ # end
189
+ class RescueJustification < Base
190
+ include Auth::AdjacentJustification
191
+ include ExceptionClassList
192
+ include RescueNode
193
+
194
+ MSG = 'This rescue needs a stated reason. A rescue claims the operation can still fail here; on ' \
195
+ 'data a validator already accepted, that claim contradicts the validator — fix the validator ' \
196
+ 'or drop the rescue. Only failures no validator of ours can prevent pass without one: a ' \
197
+ 'concurrency verdict (%<race>s) or I/O to another system (%<io>s; add a project\'s wrapper ' \
198
+ 'classes to ExpectedErrorClasses). First remedy: rescue those classes instead of ' \
199
+ 'StandardError. Otherwise state the reason in a "%<marker>s <category>: <why>" comment beside ' \
200
+ 'the rescue, category one of: %<categories>s. See ' \
201
+ 'best_practices/backend/en/01a_defensive_programming.md item 6.'.freeze
202
+
203
+ MSG_UNKNOWN_CATEGORY = '"%<marker>s %<given>s" is not a known category. Use one of: ' \
204
+ '%<categories>s.%<path_note>s'.freeze
205
+
206
+ RACE_CLASSES = NoSilentRescue::DEFAULT_EXPECTED_OUTCOME_CLASSES
207
+
208
+ IO_CLASSES = %w[
209
+ ActiveRecord::ConnectionNotEstablished ActiveRecord::NoDatabaseError
210
+ ActiveRecord::ConnectionTimeoutError Errno:: Net:: Timeout::Error IOError EOFError
211
+ SocketError OpenSSL::SSL::SSLError
212
+ ].freeze
213
+
214
+ DEFAULT_EXPECTED_ERROR_CLASSES = (RACE_CLASSES + IO_CLASSES).freeze
215
+
216
+ # Samples for the message: at most four names each, so it stays
217
+ # readable.
218
+ RACE_SAMPLE = RACE_CLASSES.first(4).join(', ').freeze
219
+ IO_SAMPLE = %w[Errno::* Net::* Timeout::Error SocketError].join(', ').freeze
220
+
221
+ DEFAULT_CATEGORIES = {
222
+ 'bulkhead' => { 'Meaning' => 'one failure unit of a batch or async sweep must not abort the ' \
223
+ 'rest; one per unit of work, reported' },
224
+ 'side-effect' => { 'Meaning' => 'a secondary effect that must not fail the primary action it rides on' },
225
+ 'degrade' => { 'Meaning' => 'a user-facing path that degrades to a fallback and reports (01a item 5)' },
226
+ 'boundary-parse' => { 'Meaning' => 'untrusted external input parsed here; the parse is the validation' },
227
+ 'surface' => { 'Meaning' => "a non-bang wrapper turning a bang method's exception into the " \
228
+ "contract's failure channel (false + errors)" },
229
+ 'delivery' => { 'Meaning' => 'a controller rendering a domain error raised below it',
230
+ 'Path' => 'app/controllers/' }
231
+ }.freeze
232
+
233
+ def on_resbody(node)
234
+ return if rescue_modifier?(node)
235
+ return if all_exceptions_listed?(node, expected_error_classes)
236
+ return if propagates?(node.body)
237
+
238
+ message = offense_message(node)
239
+ add_offense(node.loc.keyword, message: message) if message
240
+ end
241
+
242
+ private
243
+
244
+ # Any valid marker in any placement passes; otherwise the first one
245
+ # found names the problem. Only comment-only lines count above the
246
+ # rescue: a trailing comment on the previous clause's body belongs
247
+ # to that clause.
248
+ def offense_message(node)
249
+ comments = adjacent_marker_comments(node, standalone_only: true) + leading_body_marker_comments(node)
250
+ messages = comments.map { |comment| marker_message(category_word(comment)) }
251
+ return if messages.include?(nil)
252
+
253
+ messages.first || missing_reason_message
254
+ end
255
+
256
+ def marker_message(category)
257
+ return missing_reason_message if category.empty?
258
+
259
+ category_message(category)
260
+ end
261
+
262
+ # nil when the category is known and allowed in this file.
263
+ def category_message(category)
264
+ definition = categories[category]
265
+ return unknown_category_message(category, '') if definition.nil?
266
+
267
+ path = definition['Path']
268
+ return if path.nil? || processed_source.file_path.to_s.include?(path)
269
+
270
+ unknown_category_message(category, " (#{category} is only valid under #{path})")
271
+ end
272
+
273
+ # Same propagation half as NoSilentRescue's body walk: any
274
+ # `raise`/`fail`/`throw` anywhere in the body.
275
+ def propagates?(body)
276
+ return false if body.nil?
277
+
278
+ body.each_node(:send, :csend).any? do |call|
279
+ NoSilentRescue::PROPAGATING_METHODS.include?(call.method_name)
280
+ end
281
+ end
282
+
283
+ # The first word after the marker in the comment that carries it,
284
+ # lowercased, ending at whitespace or a `:` (so `bulkhead:one`
285
+ # reads `bulkhead`), a trailing `-` stripped. Empty when the marker
286
+ # ends the comment.
287
+ def category_word(comment)
288
+ text = comment.text.downcase
289
+ marker = justification_marker
290
+ rest = if marker.is_a?(Regexp)
291
+ text.match(marker)&.post_match.to_s
292
+ else
293
+ text.split(marker.downcase, 2).last.to_s
294
+ end
295
+ rest.strip.split(/[\s:]+/).first.to_s.sub(/-+\z/, '')
296
+ end
297
+
298
+ def missing_reason_message
299
+ format(MSG, race: RACE_SAMPLE, io: IO_SAMPLE, marker: justification_marker,
300
+ categories: rendered_categories)
301
+ end
302
+
303
+ def unknown_category_message(given, path_note)
304
+ format(MSG_UNKNOWN_CATEGORY, marker: justification_marker, given: given,
305
+ categories: rendered_categories, path_note: path_note)
306
+ end
307
+
308
+ def rendered_categories
309
+ categories.map { |name, definition| "#{name} (#{definition['Meaning']})" }.join(', ')
310
+ end
311
+
312
+ def categories
313
+ @categories ||= cop_config.fetch('Categories', DEFAULT_CATEGORIES).to_h do |name, definition|
314
+ [name.to_s.downcase, definition || {}]
315
+ end
316
+ end
317
+
318
+ def expected_error_classes
319
+ @expected_error_classes ||=
320
+ Array(cop_config.fetch('ExpectedErrorClasses', DEFAULT_EXPECTED_ERROR_CLASSES)) # rubocop:disable DevDoc/Style/AvoidKernelArray -- cop config accepts one class name or a list
321
+ end
322
+
323
+ def justification_marker
324
+ cop_config.fetch('JustificationMarker', 'rescue-reason:')
325
+ end
326
+ end
327
+ end
328
+ end
329
+ end
330
+ end
@@ -0,0 +1,133 @@
1
+ module RuboCop
2
+ module Cop
3
+ module DevDoc
4
+ module Style
5
+ # Route logging through `GLog` (glib-web) instead of `Rails.logger` or
6
+ # `Rollbar` directly.
7
+ #
8
+ # ## Rationale
9
+ # `GLog` is the shared logging seam: one place where destination
10
+ # (remote Rollbar vs local-only), level policy, and future redaction
11
+ # live. A call site that names its destination (`GLog.local_info` vs
12
+ # `GLog.error`) keeps that policy changeable; a direct `Rails.logger`
13
+ # or `Rollbar` call locks the destination in at the call site and
14
+ # bypasses any redaction added to the facade later.
15
+ #
16
+ # ## Rules
17
+ #
18
+ # **`Rails.logger.<any method>` is flagged** outside `module GLog`
19
+ # itself, including `::Rails.logger` and safe navigation
20
+ # (`Rails.logger&.info`). Local logging belongs behind
21
+ # `GLog.local_debug/local_info/local_warn/local_error`.
22
+ #
23
+ # **`Rollbar.<reporting method>` is flagged** — `error`, `warning`,
24
+ # `warn`, `info`, `debug`, `critical`, `log`, and the `log_*` family
25
+ # (`log_info`, `log_debug`, `log_warning`, `log_error`), which the
26
+ # rollbar gem delegates alongside the level names (`warn` and
27
+ # `warning` are both defined). A reporting send whose receiver chain
28
+ # roots at the constant — `Rollbar.scope(user).error(e)`,
29
+ # `::Rollbar.error(e)` — is flagged too. Remote reporting belongs
30
+ # behind `GLog.error/warn/info`.
31
+ #
32
+ # **`Rollbar.configure`, bare `Rollbar.scope(...)`, and other
33
+ # non-reporting calls are NOT flagged.** Configuration is setup, not
34
+ # reporting; matching every method on the constant (the local
35
+ # `Custom/UseDLog` cop this replaces did exactly that) made
36
+ # `Rollbar.configure` an offense.
37
+ #
38
+ # Calls inside `module GLog` itself are exempt — the facade routes to
39
+ # `Rails.logger` and `Rollbar` by design.
40
+ #
41
+ # **Requires glib-web >= 7.2.0** (GLog). Projects on an older
42
+ # glib-web disable this cop until they upgrade.
43
+ #
44
+ # @example
45
+ # # bad — destination locked in at the call site
46
+ # Rails.logger.info("something")
47
+ # Rollbar.error(exception)
48
+ # Rollbar.warn("degraded")
49
+ # Rollbar.log_error("message")
50
+ # Rollbar.scope(user: u).error(exception)
51
+ #
52
+ # # good — the facade owns destination and level policy
53
+ # GLog.local_info("something")
54
+ # GLog.error(exception)
55
+ # GLog.warn("degraded")
56
+ #
57
+ # # good — configuration is not reporting
58
+ # Rollbar.configure do |config|
59
+ # config.access_token = token
60
+ # end
61
+ class UseGLog < Base
62
+ MSG_RAILS_LOGGER = 'Use `GLog.local_*` instead of `Rails.logger` directly. ' \
63
+ 'GLog is the seam where destination, level policy, and ' \
64
+ 'redaction live.'.freeze
65
+
66
+ MSG_ROLLBAR = 'Use `GLog.error/warn/info` instead of `Rollbar` directly. ' \
67
+ 'GLog is the seam where destination, level policy, and ' \
68
+ 'redaction live.'.freeze
69
+
70
+ # The rollbar gem's reporting surface: the level names it delegates
71
+ # (`warn` and `warning` are both defined) plus the `log_*` family.
72
+ # `configure`, bare `scope`, and other non-reporting calls stay out —
73
+ # matching every method on the constant would flag configuration.
74
+ REPORTING_METHODS = %i[
75
+ error warning warn info debug critical log
76
+ log_info log_debug log_warning log_error
77
+ ].freeze
78
+
79
+ def on_send(node)
80
+ return if inside_g_log?(node)
81
+
82
+ if rollbar_reporting?(node)
83
+ add_offense(node, message: MSG_ROLLBAR)
84
+ elsif rails_logger?(node)
85
+ add_offense(node, message: MSG_RAILS_LOGGER)
86
+ end
87
+ end
88
+ # `Rails.logger&.info(...)` parses as a csend node.
89
+ alias on_csend on_send
90
+
91
+ private
92
+
93
+ # A reporting-named send whose receiver chain roots at the Rollbar
94
+ # constant: the direct `Rollbar.error(e)`, the cbase-spelled
95
+ # `::Rollbar.error(e)`, and scoped chains like
96
+ # `Rollbar.scope(user).error(e)`.
97
+ def rollbar_reporting?(node)
98
+ REPORTING_METHODS.include?(node.method_name) && rollbar_rooted?(node.receiver)
99
+ end
100
+
101
+ def rollbar_rooted?(node)
102
+ case node
103
+ when RuboCop::AST::ConstNode
104
+ node.const_name.to_s.sub(/\A::/, '') == 'Rollbar'
105
+ when RuboCop::AST::SendNode, RuboCop::AST::CsendNode
106
+ rollbar_rooted?(node.receiver)
107
+ else
108
+ false
109
+ end
110
+ end
111
+
112
+ # `Rails.logger.<method>`, `::Rails.logger.<method>` and the
113
+ # safe-navigated `Rails.logger&.<method>`.
114
+ def rails_logger?(node)
115
+ receiver = node.receiver
116
+ return false unless receiver.is_a?(RuboCop::AST::SendNode) || receiver.is_a?(RuboCop::AST::CsendNode)
117
+ return false unless receiver.method_name == :logger
118
+
119
+ const = receiver.receiver
120
+ const.is_a?(RuboCop::AST::ConstNode) && const.const_name.to_s.sub(/\A::/, '') == 'Rails'
121
+ end
122
+
123
+ # The facade itself routes to Rails.logger and Rollbar by design.
124
+ def inside_g_log?(node)
125
+ node.each_ancestor(:module).any? do |ancestor|
126
+ ancestor.children.first&.const_name == 'GLog'
127
+ end
128
+ end
129
+ end
130
+ end
131
+ end
132
+ end
133
+ end