super_tools 4.0.3 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,276 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SuperAirbrake
4
+ # SuperAirbrake.configure 的 DSL。
5
+ #
6
+ # 設定值的規則:沒設 → 用 gem 的預設;明確設成 nil → 不碰 Airbrake 自己的預設。
7
+ class Configuration
8
+ SETTINGS = [
9
+ :project_id, :project_key, :environment, :ignore_environments, :root_directory, :logger,
10
+ :timeout, :app_version, :sync_revision_env, :performance_stats, :query_stats, :performance_threshold_ms
11
+ ].freeze
12
+
13
+ QUERY_STATS = [nil, true, false, :skip_fast].freeze
14
+
15
+ # name: 規則名稱(Symbol,唯一)
16
+ # kind: :notice 或 :performance
17
+ # factory: Rule 子類別、其他類別、或回應 call 的物件/block
18
+ # source: :builtin、:registered、:replaced、:custom
19
+ Entry = Struct.new(:name, :kind, :enabled, :options, :factory, :source)
20
+
21
+ attr_reader :entries, :after_install_hooks, :airbrake_blocks
22
+
23
+ def initialize
24
+ @settings = {}
25
+ @entries = []
26
+ @after_install_hooks = []
27
+ @airbrake_blocks = []
28
+ @safe = true
29
+ @frozen = false
30
+ @sequence = Hash.new(0)
31
+ SuperAirbrake::BUILTIN_RULES.each do |rule_class|
32
+ @entries << Entry.new(rule_class.rule_name, rule_class.kind, rule_class.enabled_by_default, {}, rule_class, :builtin)
33
+ end
34
+ end
35
+
36
+ SETTINGS.each do |key|
37
+ define_method("#{key}=") do |value|
38
+ ensure_mutable!
39
+ validate_setting!(key, value)
40
+ @settings[key] = value
41
+ end
42
+
43
+ define_method(key) { setting(key) }
44
+ end
45
+
46
+ def set?(key)
47
+ @settings.key?(key)
48
+ end
49
+
50
+ def setting(key)
51
+ @settings.key?(key) ? @settings[key] : default_for(key)
52
+ end
53
+
54
+ def safe=(value)
55
+ ensure_mutable!
56
+ @safe = value ? true : false
57
+ end
58
+
59
+ def safe?
60
+ @safe
61
+ end
62
+
63
+ # 逃生門:拿到 Airbrake::Config 直接設 gem 沒包到的選項(只在有憑證、呼叫 Airbrake.configure 時執行)
64
+ def airbrake(&block)
65
+ raise ArgumentError, "airbrake 需要 block" unless block
66
+
67
+ ensure_mutable!
68
+ @airbrake_blocks << block
69
+ end
70
+
71
+ # 啟用規則並設定參數;沒給的參數沿用規則預設。專案 register 的規則第一次 rule 時加入。
72
+ def rule(name, **options)
73
+ ensure_mutable!
74
+ entry = find_entry(name) || add_registered(name)
75
+ entry.enabled = true
76
+ entry.options = entry.options.merge(options)
77
+ validate_entry!(entry)
78
+ entry
79
+ end
80
+
81
+ def enable(name)
82
+ ensure_mutable!
83
+ entry!(name).enabled = true
84
+ end
85
+
86
+ def disable(name)
87
+ ensure_mutable!
88
+ entry!(name).enabled = false
89
+ end
90
+
91
+ # 整條換掉(保留名稱,explain 看得到)。可以給 Rule 子類別、物件或 block。
92
+ def replace(name, callable = nil, **options, &block)
93
+ ensure_mutable!
94
+ raise ArgumentError, "replace 要給 callable 或 block(只能擇一)" if callable.nil? == block.nil?
95
+
96
+ entry = entry!(name)
97
+ entry.factory = callable || block
98
+ entry.options = entry.options.merge(options)
99
+ entry.source = :replaced
100
+ entry.enabled = true
101
+ entry
102
+ end
103
+
104
+ # 宣告式忽略:例外(可多個,字串或類別)+條件(見 Matcher::CONDITIONS),條件之間 AND、陣列內 OR。
105
+ # block 等同 if:。name:、weight: 是規則本身的參數。
106
+ def ignore(*exceptions, name: nil, weight: 0, **conditions, &block)
107
+ ensure_mutable!
108
+ if block
109
+ raise ArgumentError, "ignore 的 block 與 if: 只能擇一" if conditions.key?(:if)
110
+
111
+ conditions[:if] = block
112
+ end
113
+ matcher = Matcher.new(exceptions, conditions)
114
+ add_custom(name || next_name(:ignore), :notice, Rules::Ignore, matcher: matcher, weight: weight)
115
+ end
116
+
117
+ # notice 層級的自訂 filter:notice.ignore! 或修改 notice
118
+ def filter(name = nil, weight: 0, &block)
119
+ raise ArgumentError, "filter 需要 block" unless block
120
+
121
+ ensure_mutable!
122
+ add_custom(name || next_name(:filter), :notice, block, weight: weight)
123
+ end
124
+
125
+ def performance_filter(name = nil, weight: 0, &block)
126
+ raise ArgumentError, "performance_filter 需要 block" unless block
127
+
128
+ ensure_mutable!
129
+ add_custom(name || next_name(:performance_filter), :performance, block, weight: weight)
130
+ end
131
+
132
+ # 掛一個 filter 物件或類別(類別會用 options new 出來;Rule 子類別照 Rule 的方式建立)
133
+ def use(filter, name: nil, weight: nil, kind: nil, **options)
134
+ ensure_mutable!
135
+ kind ||= filter.respond_to?(:kind) ? filter.kind : :notice
136
+ raise ArgumentError, "kind 只能是 #{Rule::KINDS.inspect}" unless Rule::KINDS.include?(kind)
137
+
138
+ options = options.merge(weight: weight) unless weight.nil?
139
+ default_name = filter.respond_to?(:rule_name) && filter.rule_name
140
+ add_custom(name || default_name || next_name(:use), kind, filter, options)
141
+ end
142
+
143
+ # 規則都掛好之後呼叫,參數是 notifier(預設 Airbrake)
144
+ def after_install(&block)
145
+ raise ArgumentError, "after_install 需要 block" unless block
146
+
147
+ ensure_mutable!
148
+ @after_install_hooks << block
149
+ end
150
+
151
+ def entry(name)
152
+ find_entry(name)
153
+ end
154
+
155
+ def freeze!
156
+ @frozen = true
157
+ self
158
+ end
159
+
160
+ def frozen_config?
161
+ @frozen
162
+ end
163
+
164
+ def rules_summary
165
+ @entries.map do |entry|
166
+ { name: entry.name, kind: entry.kind, enabled: entry.enabled, source: entry.source, options: describe_options(entry) }
167
+ end
168
+ end
169
+
170
+ def explain
171
+ lines = ["SuperAirbrake 規則(依註冊順序):"]
172
+ @entries.each do |entry|
173
+ status = entry.enabled ? "開" : "關"
174
+ options = describe_options(entry)
175
+ detail = options.map { |key, value| "#{key}=#{explain_value(key, value)}" }.join(", ")
176
+ lines << format(" [%s] %-22s %-11s %-9s %s", status, entry.name, entry.kind, entry.source, detail).rstrip
177
+ end
178
+ lines << "設定:performance_threshold_ms=#{performance_threshold_ms.inspect}, query_stats=#{query_stats.inspect}, " \
179
+ "performance_stats=#{performance_stats.inspect}, ignore_environments=#{ignore_environments.inspect}, safe=#{@safe}"
180
+ lines.join("\n")
181
+ end
182
+
183
+ private
184
+
185
+ def default_for(key)
186
+ case key
187
+ when :environment
188
+ ::Rails.env.to_s if defined?(::Rails) && ::Rails.respond_to?(:env)
189
+ when :ignore_environments
190
+ %w[development test]
191
+ when :root_directory
192
+ ::Rails.root if defined?(::Rails) && ::Rails.respond_to?(:root)
193
+ when :logger
194
+ default_logger
195
+ when :app_version
196
+ ENV["APP_REVISION"].presence
197
+ when :sync_revision_env
198
+ true
199
+ when :performance_threshold_ms
200
+ 1500
201
+ end
202
+ end
203
+
204
+ def default_logger
205
+ if defined?(::Airbrake::Rails) && ::Airbrake::Rails.respond_to?(:logger) && defined?(::Rails) && ::Rails.respond_to?(:root) && ::Rails.root
206
+ ::Airbrake::Rails.logger
207
+ elsif defined?(::Rails) && ::Rails.respond_to?(:logger) && ::Rails.logger
208
+ ::Rails.logger
209
+ end
210
+ end
211
+
212
+ def validate_setting!(key, value)
213
+ case key
214
+ when :query_stats
215
+ raise ArgumentError, "query_stats 只能是 #{QUERY_STATS.inspect}" unless QUERY_STATS.include?(value)
216
+ when :performance_threshold_ms
217
+ raise ArgumentError, "performance_threshold_ms 要是數字" unless value.nil? || value.is_a?(Numeric)
218
+ end
219
+ end
220
+
221
+ def ensure_mutable!
222
+ raise ConfigurationFrozen, "SuperAirbrake 已經安裝完成,設定不能再改" if @frozen
223
+ end
224
+
225
+ def find_entry(name)
226
+ @entries.find { |entry| entry.name == name.to_sym }
227
+ end
228
+
229
+ def entry!(name)
230
+ find_entry(name) || raise(UnknownRule, "沒有名為 #{name} 的規則(已知:#{@entries.map(&:name).join(', ')})")
231
+ end
232
+
233
+ def add_registered(name)
234
+ rule_class = Rule.lookup(name)
235
+ raise UnknownRule, "沒有名為 #{name} 的規則,自訂規則要先 SuperAirbrake.register" unless rule_class
236
+
237
+ entry = Entry.new(rule_class.rule_name, rule_class.kind, true, {}, rule_class, :registered)
238
+ @entries << entry
239
+ entry
240
+ end
241
+
242
+ def add_custom(name, kind, factory, options)
243
+ name = name.to_sym
244
+ raise ArgumentError, "規則名稱 #{name} 重複" if find_entry(name)
245
+
246
+ entry = Entry.new(name, kind, true, options, factory, :custom)
247
+ validate_entry!(entry)
248
+ @entries << entry
249
+ entry
250
+ end
251
+
252
+ # Rule 子類別在設定當下就檢查參數,打錯字不用等到上線才發現
253
+ def validate_entry!(entry)
254
+ factory = entry.factory
255
+ factory.new(entry.options, self) if factory.is_a?(Class) && factory <= Rule
256
+ end
257
+
258
+ def next_name(prefix)
259
+ @sequence[prefix] += 1
260
+ :"#{prefix}_#{@sequence[prefix]}"
261
+ end
262
+
263
+ def explain_value(key, value)
264
+ return value if key == :matcher
265
+ return "<proc>" if value.respond_to?(:call)
266
+
267
+ value.inspect
268
+ end
269
+
270
+ def describe_options(entry)
271
+ entry.options.each_with_object({}) do |(key, value), result|
272
+ result[key] = value.is_a?(Matcher) ? value.describe : value
273
+ end
274
+ end
275
+ end
276
+ end
@@ -0,0 +1,108 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SuperAirbrake
4
+ # 把 Configuration 套到 Airbrake:
5
+ # 1. 有憑證才 Airbrake.configure
6
+ # 2. 套 query_stats(不論有沒有憑證)
7
+ # 3. 依順序掛規則(沒有憑證也掛,Airbrake 沒設定時不會送出任何東西)
8
+ # 4. after_install hooks
9
+ # 5. 凍結設定
10
+ class Installer
11
+ attr_reader :config, :notifier, :airbrake_config, :installed
12
+
13
+ def initialize(config, notifier:, airbrake_config:)
14
+ @config = config
15
+ @notifier = notifier
16
+ @airbrake_config = airbrake_config
17
+ @installed = []
18
+ end
19
+
20
+ def install
21
+ configure_airbrake if credentials?
22
+ apply_query_stats
23
+ install_rules
24
+ config.after_install_hooks.each { |hook| hook.call(notifier) }
25
+ config.freeze!
26
+ self
27
+ end
28
+
29
+ def credentials?
30
+ config.project_id.to_s.strip != "" && config.project_key.to_s.strip != ""
31
+ end
32
+
33
+ def logger
34
+ config.logger
35
+ end
36
+
37
+ # referer_blocklist 沿用 blocklist 的 keys(就算 blocklist 被停用或取代也一樣)
38
+ def blocklist_patterns
39
+ @blocklist_patterns ||= begin
40
+ entry = config.entry(:blocklist)
41
+ Rules::Blocklist.new(entry ? entry.options : {}, config).patterns
42
+ end
43
+ end
44
+
45
+ private
46
+
47
+ def configure_airbrake
48
+ notifier.configure do |c|
49
+ c.project_id = config.project_id
50
+ c.project_key = config.project_key
51
+ [:environment, :ignore_environments, :root_directory, :logger, :timeout, :app_version, :performance_stats].each do |key|
52
+ value = config.setting(key)
53
+ c.public_send("#{key}=", value) unless value.nil?
54
+ end
55
+ config.airbrake_blocks.each { |block| block.call(c) }
56
+ end
57
+
58
+ # `rake airbrake:deploy` 只讀 ENV["REVISION"];Kamal 容器內沒有 .git
59
+ ENV["REVISION"] ||= config.app_version.to_s if config.sync_revision_env && config.app_version.present?
60
+ end
61
+
62
+ def apply_query_stats
63
+ case config.query_stats
64
+ when true, false
65
+ airbrake_config.query_stats = config.query_stats
66
+ when :skip_fast
67
+ SkipFastQuery.install!(config.performance_threshold_ms)
68
+ end
69
+ end
70
+
71
+ def install_rules
72
+ config.entries.each do |entry|
73
+ next unless entry.enabled
74
+
75
+ filter = build(entry)
76
+ next if filter.nil?
77
+
78
+ wrapped = SafeFilter.new(entry.name, filter, logger: logger, weight: weight_for(entry, filter), safe: config.safe?)
79
+ if entry.kind == :performance
80
+ notifier.add_performance_filter(wrapped)
81
+ else
82
+ notifier.add_filter(wrapped)
83
+ end
84
+ @installed << wrapped
85
+ end
86
+ end
87
+
88
+ def build(entry)
89
+ factory = entry.factory
90
+ if factory.is_a?(Class) && factory <= Rule
91
+ factory.new(entry.options, config).build(self)
92
+ elsif factory.is_a?(Class)
93
+ options = entry.options.reject { |key, _| key == :weight }
94
+ options.empty? ? factory.new : factory.new(**options)
95
+ elsif factory.respond_to?(:call)
96
+ factory
97
+ else
98
+ raise ArgumentError, "規則 #{entry.name} 不是 Rule、類別或 callable"
99
+ end
100
+ end
101
+
102
+ def weight_for(entry, filter)
103
+ return entry.options[:weight] if entry.options.key?(:weight) && !entry.options[:weight].nil?
104
+
105
+ filter.respond_to?(:weight) ? filter.weight : 0
106
+ end
107
+ end
108
+ end
@@ -0,0 +1,134 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SuperAirbrake
4
+ # c.ignore 的條件比對。
5
+ # - 不同條件之間是 AND;同一條件給陣列是 OR。
6
+ # - 例外與 controller 可以給字串,比對的是類別與祖先的名稱,不會觸發 autoload
7
+ # (initializer 比 eager_load 早跑,這時 Admin::BaseController 可能還沒載入)。
8
+ class Matcher
9
+ CONDITIONS = [:status, :web, :controller, :controller_path, :path, :host, :message, :job, :if, :unless].freeze
10
+
11
+ attr_reader :exceptions, :conditions
12
+
13
+ def initialize(exceptions = [], conditions = {})
14
+ unknown = conditions.keys - CONDITIONS
15
+ raise ArgumentError, "ignore 不認得的條件:#{unknown.join(', ')}(可用:#{CONDITIONS.join(', ')})" unless unknown.empty?
16
+
17
+ @exceptions = Array(exceptions).flatten
18
+ @conditions = conditions
19
+ end
20
+
21
+ def match?(notice)
22
+ exception = notice.stash[:exception]
23
+ return false unless exception_match?(exception)
24
+
25
+ CONDITIONS.each do |key|
26
+ next if key == :unless || !@conditions.key?(key)
27
+ return false unless condition_match?(key, @conditions[key], notice, exception)
28
+ end
29
+
30
+ return false if @conditions.key?(:unless) && @conditions[:unless].call(notice)
31
+
32
+ true
33
+ end
34
+
35
+ def describe
36
+ parts = []
37
+ parts << @exceptions.map { |e| e.is_a?(Module) ? e.name : e.to_s }.join(" | ") unless @exceptions.empty?
38
+ @conditions.each do |key, value|
39
+ parts << "#{key}=#{value.respond_to?(:call) ? '<proc>' : value.inspect}"
40
+ end
41
+ parts.empty? ? "(全部)" : parts.join(" ")
42
+ end
43
+
44
+ class << self
45
+ # Rails 對這個例外回的 HTTP status(依 rescue_responses,含專案自己加的對應);沒有 ActionDispatch 時回 nil
46
+ def status_for(exception)
47
+ return nil unless exception && defined?(::ActionDispatch::ExceptionWrapper)
48
+
49
+ ::ActionDispatch::ExceptionWrapper.status_code_for_exception(exception.class.name)
50
+ end
51
+
52
+ def rack_request(notice)
53
+ notice.stash[:rack_request]
54
+ end
55
+
56
+ def controller(notice)
57
+ request = rack_request(notice)
58
+ return nil unless request && request.respond_to?(:env)
59
+
60
+ request.env["action_controller.instance"]
61
+ end
62
+
63
+ # Sidekiq 的 notice 在 params[:job]("wrapped" 是 ActiveJob 包裝前的類別),ActiveJob 的在 params[:job_class]
64
+ def job_name(notice)
65
+ params = notice[:params] || {}
66
+ job = params[:job] || params["job"]
67
+ if job.is_a?(Hash)
68
+ (job["wrapped"] || job[:wrapped] || job["class"] || job[:class]).to_s.presence
69
+ else
70
+ (params[:job_class] || params["job_class"]).to_s.presence
71
+ end
72
+ end
73
+
74
+ def kind_of_name?(object, expected)
75
+ return object.is_a?(expected) if expected.is_a?(Module)
76
+
77
+ object.class.ancestors.any? { |ancestor| ancestor.name == expected.to_s }
78
+ end
79
+ end
80
+
81
+ private
82
+
83
+ def exception_match?(exception)
84
+ return true if @exceptions.empty?
85
+ return false unless exception
86
+
87
+ @exceptions.any? { |expected| self.class.kind_of_name?(exception, expected) }
88
+ end
89
+
90
+ def condition_match?(key, expected, notice, exception)
91
+ case key
92
+ when :status
93
+ Array(expected).include?(self.class.status_for(exception))
94
+ when :web
95
+ (!self.class.rack_request(notice).nil?) == (expected ? true : false)
96
+ when :controller
97
+ controller = self.class.controller(notice)
98
+ controller ? Array(expected).any? { |e| self.class.kind_of_name?(controller, e) } : false
99
+ when :controller_path
100
+ controller = self.class.controller(notice)
101
+ return false unless controller && controller.respond_to?(:controller_path)
102
+
103
+ any_value?(expected, controller.controller_path.to_s, :prefix)
104
+ when :path
105
+ request = self.class.rack_request(notice)
106
+ request && request.respond_to?(:path) ? any_value?(expected, request.path.to_s, :prefix) : false
107
+ when :host
108
+ request = self.class.rack_request(notice)
109
+ request && request.respond_to?(:host) ? any_value?(expected, request.host.to_s, :exact) : false
110
+ when :message
111
+ exception ? any_value?(expected, exception.message.to_s, :include) : false
112
+ when :job
113
+ name = self.class.job_name(notice)
114
+ name ? any_value?(Array(expected).map { |e| e.is_a?(Module) ? e.name : e }, name, :exact) : false
115
+ when :if
116
+ expected.call(notice) ? true : false
117
+ end
118
+ end
119
+
120
+ def any_value?(expected, actual, string_mode)
121
+ Array(expected).any? do |value|
122
+ if value.is_a?(Regexp)
123
+ value.match?(actual)
124
+ else
125
+ case string_mode
126
+ when :prefix then actual.start_with?(value.to_s)
127
+ when :include then actual.include?(value.to_s)
128
+ else actual == value.to_s
129
+ end
130
+ end
131
+ end
132
+ end
133
+ end
134
+ end
@@ -0,0 +1,106 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SuperAirbrake
4
+ # 規則基底類別。內建規則與專案自訂規則都繼承它:
5
+ #
6
+ # class NoisyHost < SuperAirbrake::Rule
7
+ # rule_name :noisy_host
8
+ # defaults hosts: []
9
+ #
10
+ # def call(notice)
11
+ # request = notice.stash[:rack_request]
12
+ # notice.ignore! if request && options[:hosts].include?(request.host)
13
+ # end
14
+ # end
15
+ # SuperAirbrake.register(NoisyHost)
16
+ class Rule
17
+ KINDS = [:notice, :performance].freeze
18
+
19
+ class << self
20
+ def rule_name(name = nil)
21
+ @rule_name = name.to_sym if name
22
+ defined?(@rule_name) ? @rule_name : nil
23
+ end
24
+
25
+ def defaults(hash = nil)
26
+ @defaults = hash.freeze if hash
27
+ (defined?(@defaults) && @defaults) || {}
28
+ end
29
+
30
+ # :notice(錯誤通報)或 :performance(效能事件)
31
+ def kind(value = nil)
32
+ if value
33
+ raise ArgumentError, "kind 只能是 #{KINDS.inspect}" unless KINDS.include?(value)
34
+
35
+ @kind = value
36
+ end
37
+ (defined?(@kind) && @kind) || :notice
38
+ end
39
+
40
+ def enabled_by_default(value = nil)
41
+ @enabled_by_default = value unless value.nil?
42
+ defined?(@enabled_by_default) && @enabled_by_default ? true : false
43
+ end
44
+
45
+ def required_options(*keys)
46
+ @required_options = keys unless keys.empty?
47
+ (defined?(@required_options) && @required_options) || []
48
+ end
49
+
50
+ def registry
51
+ return Rule.instance_variable_get(:@registry) if Rule.instance_variable_defined?(:@registry)
52
+
53
+ Rule.instance_variable_set(:@registry, {})
54
+ end
55
+
56
+ def register(rule_class)
57
+ name = rule_class.respond_to?(:rule_name) && rule_class.rule_name
58
+ raise ArgumentError, "#{rule_class} 沒有設定 rule_name" unless name
59
+
60
+ registry[name] = rule_class
61
+ end
62
+
63
+ def lookup(name)
64
+ registry[name.to_sym]
65
+ end
66
+ end
67
+
68
+ attr_reader :options, :config
69
+
70
+ def initialize(options = {}, config = nil)
71
+ @options = self.class.defaults.merge(options || {})
72
+ @config = config
73
+ validate!
74
+ end
75
+
76
+ def name
77
+ self.class.rule_name
78
+ end
79
+
80
+ def weight
81
+ @options.fetch(:weight, 0)
82
+ end
83
+
84
+ # 回傳要掛到 Airbrake 的 filter(預設就是自己);回傳 nil 代表這個環境不用掛
85
+ def build(_installer)
86
+ self
87
+ end
88
+
89
+ def call(_target)
90
+ raise NotImplementedError, "#{self.class} 要實作 call"
91
+ end
92
+
93
+ private
94
+
95
+ def validate!
96
+ missing = self.class.required_options.select { |key| @options[key].nil? }
97
+ return if missing.empty?
98
+
99
+ raise ArgumentError, "規則 #{name} 缺少參數:#{missing.join(', ')}"
100
+ end
101
+
102
+ def ancestor_named?(object, name)
103
+ object.class.ancestors.any? { |ancestor| ancestor.name == name.to_s }
104
+ end
105
+ end
106
+ end
@@ -0,0 +1,57 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SuperAirbrake
4
+ module Rules
5
+ # 遮掉 params/session/headers/context.url 裡的敏感 key。
6
+ #
7
+ # source:
8
+ # :rails_filter_parameters(預設)用 Rails 的 filter_parameters,延後到第一次通報才讀
9
+ # (initializer 比 filter_parameter_logging.rb 早載入,當下還不完整)
10
+ # :static 只用 keys
11
+ # keys: 額外的 key。Regexp 原樣;String/Symbol 轉成不分大小寫的部分比對
12
+ # (Airbrake 對 Symbol/String 是完全相等,:passw 擋不到 password)
13
+ # authorization: 補上 /authorization/i(filter_parameters 沒涵蓋 Authorization header)
14
+ class Blocklist < Rule
15
+ SOURCES = [:rails_filter_parameters, :static].freeze
16
+
17
+ rule_name :blocklist
18
+ enabled_by_default true
19
+ defaults source: :rails_filter_parameters, keys: [], authorization: true, filter_parameters: nil
20
+
21
+ def self.normalize(patterns)
22
+ patterns.map { |pattern| pattern.is_a?(Regexp) ? pattern : /#{Regexp.escape(pattern.to_s)}/i }
23
+ end
24
+
25
+ def patterns
26
+ base = options[:source] == :static ? [] : rails_filter_parameters
27
+ list = self.class.normalize(base + Array(options[:keys]))
28
+ list << /authorization/i if options[:authorization]
29
+ list.uniq
30
+ end
31
+
32
+ # KeysBlocklist 的 weight 是 -110:不論何時註冊都最後跑,其他規則看得到原值
33
+ def build(_installer)
34
+ rule = self
35
+ ::Airbrake::Filters::KeysBlocklist.new([-> { rule.patterns }])
36
+ end
37
+
38
+ private
39
+
40
+ def validate!
41
+ super
42
+ return if SOURCES.include?(options[:source])
43
+
44
+ raise ArgumentError, "blocklist 的 source 只能是 #{SOURCES.inspect}"
45
+ end
46
+
47
+ def rails_filter_parameters
48
+ custom = options[:filter_parameters]
49
+ return Array(custom.call) if custom.respond_to?(:call)
50
+ return Array(custom) if custom
51
+ return [] unless defined?(::Rails) && ::Rails.respond_to?(:application) && ::Rails.application
52
+
53
+ Array(::Rails.application.config.filter_parameters)
54
+ end
55
+ end
56
+ end
57
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SuperAirbrake
4
+ module Rules
5
+ # 通報附上登入者資訊,內容由專案的 lambda 決定;lambda 出錯時不附、照常通報
6
+ class CurrentSession < Rule
7
+ rule_name :current_session
8
+ enabled_by_default false
9
+ defaults key: :current_session
10
+ required_options :with
11
+
12
+ def call(notice)
13
+ notice[:context][options[:key]] = options[:with].call
14
+ rescue StandardError
15
+ nil
16
+ end
17
+ end
18
+ end
19
+ end