diff --git a/lib/oauth2/access_token.rb b/lib/oauth2/access_token.rb index df482c5f..6382bc33 100644 --- a/lib/oauth2/access_token.rb +++ b/lib/oauth2/access_token.rb @@ -157,9 +157,10 @@ def initialize(client, token, opts = {}) no_tokens = (@token.nil? || @token.empty?) && (@refresh_token.nil? || @refresh_token.empty?) if no_tokens if @client.options[:raise_errors] + sanitized_opts = opts.is_a?(Hash) ? sanitize_opts(opts) : opts raise Error.new({ error: "OAuth2::AccessToken has no token", - error_description: "Options are: #{opts.inspect}", + error_description: "Options are: #{sanitized_opts.inspect}", }) elsif !OAuth2.config.silence_no_tokens_warning warn("OAuth2::AccessToken has no token") @@ -419,5 +420,28 @@ def convert_expires_at(expires_at) rescue ArgumentError expires_at.to_i end + + def sanitize_opts(hash) + label = (defined?(AUTH_SANITIZER) && AUTH_SANITIZER.respond_to?(:filtered_label)) ? AUTH_SANITIZER.filtered_label : "[FILTERED]" + hash.each_with_object({}) do |(key, value), acc| + acc[key] = + if sensitive_opts_key?(key) + label + elsif value.is_a?(Hash) + sanitize_opts(value) + else + value + end + end + end + + def sensitive_opts_key?(key) + k = key.to_s.downcase + filtered_keys = (defined?(AUTH_SANITIZER) && AUTH_SANITIZER.respond_to?(:default_filtered_keys)) ? AUTH_SANITIZER.default_filtered_keys : %w[access_token refresh_token id_token client_secret assertion code_verifier token] + return true if filtered_keys.include?(k) + return true if TOKEN_KEY_LOOKUP.any? { |tk| tk.to_s.casecmp(k).zero? } + + k.include?("secret") || k.include?("password") || k.end_with?("token") + end end end diff --git a/spec/oauth2/access_token_spec.rb b/spec/oauth2/access_token_spec.rb index a3e8d051..7c40c841 100644 --- a/spec/oauth2/access_token_spec.rb +++ b/spec/oauth2/access_token_spec.rb @@ -679,6 +679,19 @@ def assert_initialized_token(target) it "raises on initialize" do block_is_expected.to raise_error(OAuth2::Error, {error: "OAuth2::AccessToken has no token", error_description: "Options are: #{{raise_errors: true}}"}.to_s) end + + context "when options contain sensitive parameters" do + let(:options) { {raise_errors: true, id_token: "jwt.secret.payload", client_secret: "topsecret"} } + + it "redacts sensitive parameter values in error description" do + block_is_expected.to raise_error(OAuth2::Error) do |err| + expect(err.message).to include("id_token") + expect(err.message).to include("[FILTERED]") + expect(err.message).not_to include("jwt.secret.payload") + expect(err.message).not_to include("topsecret") + end + end + end end context "when there is refresh_token" do