Ruby版Honeybadger属性过滤失效问题求助
Rails Honeybadger 嵌套异常敏感字段泄露解决方案
已配置Honeybadger错误监控的Rails应用中,即便在config/honeybadger.yml的filter_keys列表和config/initializers/filter_parameter_logging.rb中添加了敏感字段,这些信息仍会在错误报告的Backtrace > Nested Exceptions下泄露。例如ActiveRecord::RecordNotUnique异常的SQL语句中,authentication_token等敏感值未被过滤:
ActiveRecord::RecordNotUnique: Mysql2::Error: Duplicate entry 'test@email.com' for key 'index_users_on_email': INSERT INTO `users` (`encrypted_password`, `confirmed_at`, `authentication_token`, `created_at`, `updated_at`, `locale`, `provider`, `uid`, `app`, `email`, `first_name`, `last_name`, `location`, `latitude`, `longitude`, `region`, `state`, `password_set_at`) VALUES ([password shown but redadcted], '2023-03-23 16:58:08', '[authentication_token shown]', '2023-03-23 16:58:08', '2023-03-23 16:58:08', 'en', [provider], [uid], [app], 'test@email.com', 'Jane', 'Doe', [city, state], []lat, [long], [region], [state], '2023-03-23 16:58:08')
核心原因
Honeybadger默认的参数过滤仅针对请求参数(params对象),而嵌套异常中的SQL错误消息属于数据库返回的原始异常内容,不在默认过滤范围内。
解决方法
1. 自定义Honeybadger异常过滤器
在config/initializers/honeybadger.rb中添加自定义过滤逻辑,遍历异常链替换敏感字段:
Honeybadger.exception_filter do |notice| notice.exceptions.each do |exception| next unless exception.message.present? # 替换authentication_token(假设是64位十六进制字符串) filtered_msg = exception.message.gsub(/'[a-f0-9]{64}'/, '[FILTERED]') # 替换加密密码相关内容 filtered_msg = filtered_msg.gsub(/\[password shown but redacted\]/, '[FILTERED]') # 可根据实际敏感字段添加更多正则匹配 # 比如替换其他敏感值:filtered_msg = filtered_msg.gsub(/'secret-value'/, '[FILTERED]') exception.message = filtered_msg end notice end
2. 在ActiveRecord层提前过滤错误消息
通过扩展数据库错误类,在异常抛出前就过滤SQL中的敏感内容,创建config/initializers/active_record_error_filter.rb:
module ActiveRecordErrorFilter def initialize(message = nil, sql = nil, binds = nil) if sql.present? # 过滤SQL VALUES子句中的敏感值 filtered_sql = sql.gsub(/VALUES \([^)]+\)/) do |values_section| values_section.gsub(/'[a-f0-9]{64}'/, '[FILTERED]') .gsub(/\[password shown but redacted\]/, '[FILTERED]') end super(message, filtered_sql, binds) else super end end end # 将过滤逻辑注入到Mysql2错误类 Mysql2::Error.prepend(ActiveRecordErrorFilter)
3. 确认Honeybadger基础配置完整性
确保config/honeybadger.yml中启用过滤并包含所有需要过滤的请求参数:
production: enable_filtering: true filter_keys: - authentication_token - encrypted_password - password - credit_card # 添加其他需要过滤的请求参数字段
内容的提问来源于stack exchange,提问作者Genevieve McAllister
相关产品推荐
相关产品推荐

