如何在日志记录中过滤部分路径(而不是参数)?

人气:1,038 发布:2022-10-16 标签: security ruby-on-rails ruby-on-rails-5

问题描述

在我的路线中,我有一个类似于GET 'check/:secret的路线。

当我向日志中的该路由发送请求时,我看到:

Started GET "/check/the-secret-here" for ::1 at 2021-01-14 16:38:01 -0600
...

我想对密码进行筛选/密文处理,使其看起来像:

Started GET "/check/[FILTERED]" for ::1 at 2021-01-14 16:38:01 -0600
...

我使用的是rails 5.1,我添加了config.filter_parameters += %i[secret],它只筛选POST参数上的值。

推荐答案

您描述的不是参数,而是URL的一部分。 如果您将您的秘密作为可在任何地方共享的URL的一部分公开,则可能不会像您预期的那样如此秘密,因此将该操作更改为POST请求可能是个好主意? 无论如何,如果有任何强有力的理由让它保持这种方式,我能看到的唯一一件事就是用猴子修补您的Rails实例,特别是ActionDispatch::Http::FilterParameters。因此,添加到您的config/initializers文件夹:

module ActionDispatch
  module Http
    module FilterParameters
      def filtered_path
        # Keep an eye here adding a really good filtering regex, or potentially
        # you'll filter more than you were expecting
        secret_path = path.gsub(//the-secret-here//, "/[FILTERED]/")
        @filtered_path ||= query_string.empty? ? secret_path : "#{secret_path}?#{filtered_query_string}"
      end
    end
  end
end

356