From 18f0d9dc9483d822612cffb54a44a28be52d5e57 Mon Sep 17 00:00:00 2001 From: Oliver Lazoroski Date: Wed, 25 Nov 2026 12:07:56 +0100 Subject: [PATCH] fix(security): redact caller query params and escape control chars in logs [SEC-2535] --- lib/getstream_ruby/client.rb | 28 +++++----- lib/getstream_ruby/configuration.rb | 5 +- lib/getstream_ruby/log_redaction.rb | 17 +++++++ lib/getstream_ruby/request_logging.rb | 24 ++++++--- spec/logging_spec.rb | 73 +++++++++++++++++++++++++++ 5 files changed, 125 insertions(+), 22 deletions(-) diff --git a/lib/getstream_ruby/client.rb b/lib/getstream_ruby/client.rb index c2ea8408..cead87a0 100644 --- a/lib/getstream_ruby/client.rb +++ b/lib/getstream_ruby/client.rb @@ -198,29 +198,29 @@ def wait_for_task(task_id, poll_interval: 1, timeout: 60) end def make_request(method, path, query_params: nil, body: nil, request_timeout: nil) - # Handle query parameters - if query_params && !query_params.empty? - query_string = query_params.map { |k, v| "#{k}=#{query_value(v)}" }.join('&') - path = "#{path}?#{query_string}" - end - - # Make the request - request(method, path, body, request_timeout: request_timeout) + # Query params stay a Hash all the way to Faraday (which URL-encodes + # them) instead of being baked into `path`, so request logging sees + # them as params and can redact them. + params = (query_params || {}).to_h { |k, v| [k.to_s, query_value(v)] } + request(method, path, body, request_timeout: request_timeout, query_params: params) end private + # Serializes one query value to its wire string, unencoded (Faraday + # URL-encodes it): times as RFC 3339, scalar lists comma-separated, + # anything structured as JSON. def query_value(value) - return URI.encode_www_form_component(value.iso8601(9)) if value.is_a?(Time) || value.is_a?(DateTime) - return URI.encode_www_form_component(value) unless [Array, Hash, GetStream::BaseModel].any? { |k| value.is_a?(k) } + return value.iso8601(9) if value.is_a?(Time) || value.is_a?(DateTime) + return value.to_s unless [Array, Hash, GetStream::BaseModel].any? { |k| value.is_a?(k) } scalars = value.is_a?(Array) && value.all? { |e| e.is_a?(String) || e.is_a?(Numeric) || e == true || e == false } - URI.encode_www_form_component(scalars ? value.join(',') : value.to_json) + scalars ? value.join(',') : value.to_json end - def request(method, path, data = {}, request_timeout: nil) - # Add API key to query parameters - query_params = { api_key: @configuration.api_key } + def request(method, path, data = {}, request_timeout: nil, query_params: {}) + # The SDK's own api_key always wins over a caller-supplied one. + query_params = query_params.merge('api_key' => @configuration.api_key) # Check if this is a file upload request that needs multipart return make_multipart_request(method, path, query_params, data) if multipart_request?(data) diff --git a/lib/getstream_ruby/configuration.rb b/lib/getstream_ruby/configuration.rb index 5130f901..a3b6cad2 100644 --- a/lib/getstream_ruby/configuration.rb +++ b/lib/getstream_ruby/configuration.rb @@ -83,7 +83,10 @@ def log_pool_config_to(logger) def warn_pool_fallback(fallback_adapter, error) warn_logger = @logger || Logger.new($stdout).tap { |l| l.level = Logger::WARN } warn_logger.warn( - "Falling back to #{fallback_adapter}: could not configure net_http_persistent (#{error.message})", + LogRedaction.sanitize( + "Falling back to #{fallback_adapter}: could not configure net_http_persistent " \ + "(#{LogRedaction.redact_message(error.message)})", + ), ) end diff --git a/lib/getstream_ruby/log_redaction.rb b/lib/getstream_ruby/log_redaction.rb index 119206a0..0bf5334e 100644 --- a/lib/getstream_ruby/log_redaction.rb +++ b/lib/getstream_ruby/log_redaction.rb @@ -14,6 +14,10 @@ module LogRedaction # free-form string (e.g. a transport error message that embeds the request # URL), value runs up to the next `&`, whitespace, or end of string. MESSAGE_SECRET_PATTERN = /\b(#{QUERY_PARAMS.join('|')})=[^&\s]*/i.freeze + # Control characters (C0, DEL, C1) plus the Unicode line/paragraph + # separators: anything a log sink or viewer may treat as a line break or + # terminal escape. + CONTROL_CHARS = /[[:cntrl:]

]/.freeze module_function @@ -53,6 +57,19 @@ def redact_message(string) string.gsub(MESSAGE_SECRET_PATTERN) { "#{Regexp.last_match(1)}=#{REDACTED}" } end + # Makes a log line single-line and inert: every control character is + # replaced by its escaped form (CR -> `\r`, LF -> `\n`, ESC -> `\e`, ...), + # so a value echoed into a log event (path, query, error message, body) + # can't forge extra log lines or inject terminal escape sequences. + # Non-UTF-8 input (e.g. a binary response body) is scrubbed first so the + # match itself can't raise. + def sanitize(value) + string = value.to_s + string = string.dup.force_encoding(Encoding::UTF_8) unless string.encoding == Encoding::UTF_8 + string = string.scrub unless string.valid_encoding? + string.gsub(CONTROL_CHARS) { |char| char.dump[1..-2] } + end + end end diff --git a/lib/getstream_ruby/request_logging.rb b/lib/getstream_ruby/request_logging.rb index fce212af..80e89c71 100644 --- a/lib/getstream_ruby/request_logging.rb +++ b/lib/getstream_ruby/request_logging.rb @@ -29,9 +29,9 @@ def log_request_sent(method, path, query_params, body_json = nil) return unless logger query = LogRedaction.redact_query(query_params).map { |k, v| "#{k}=#{v}" }.join('&') - line = +"http.request.sent http.request.method=#{method} url.path=#{path} url.query=#{query}" + line = +"http.request.sent http.request.method=#{method} url.path=#{log_path(path)} url.query=#{query}" line << " http.request.body=#{LogRedaction.redact_json_body(body_json)}" if @configuration.log_bodies && body_json - logger.debug { line } + logger.debug { LogRedaction.sanitize(line) } end def log_response_received(response, started) @@ -42,7 +42,7 @@ def log_response_received(response, started) line = +"http.response.received http.response.status_code=#{response.status} " \ "http.response.body.size=#{raw_body.bytesize} duration_ms=#{elapsed_ms(started)}" line << " http.response.body=#{LogRedaction.redact_json_body(raw_body)}" if @configuration.log_bodies - logger.debug { line } + logger.debug { LogRedaction.sanitize(line) } end def log_request_failed(method, path, error, started) @@ -53,8 +53,10 @@ def log_request_failed(method, path, error, started) message = LogRedaction.redact_message(error.message) logger.error do - "http.request.failed http.request.method=#{method} url.path=#{path} " \ - "error.type=#{error_type} error.message=#{message} duration_ms=#{elapsed_ms(started)}" + LogRedaction.sanitize( + "http.request.failed http.request.method=#{method} url.path=#{log_path(path)} " \ + "error.type=#{error_type} error.message=#{message} duration_ms=#{elapsed_ms(started)}", + ) end end @@ -70,10 +72,18 @@ def log_retry_attempt(method, path, error, attempt, started) return unless logger message = LogRedaction.redact_message(error.message) - line = +"http.request.failed http.request.method=#{method} url.path=#{path} retry.attempt=#{attempt + 1}" + line = +"http.request.failed http.request.method=#{method} url.path=#{log_path(path)} " \ + "retry.attempt=#{attempt + 1}" line << " error.type=#{error.error_type}" if error.is_a?(TransportError) line << " error.message=#{message} duration_ms=#{elapsed_ms(started)}" - logger.debug { line } + logger.debug { LogRedaction.sanitize(line) } + end + + # Query params travel separately (see Client#request), so `path` is + # normally query-free; a caller-built path like `post('/x?token=...')` + # still gets its secret values scrubbed. + def log_path(path) + LogRedaction.redact_message(path.to_s) end def elapsed_ms(started) diff --git a/spec/logging_spec.rb b/spec/logging_spec.rb index 7ccc9e68..60af7de8 100644 --- a/spec/logging_spec.rb +++ b/spec/logging_spec.rb @@ -128,4 +128,77 @@ def recorder end + # SEC-2535: caller query params used to be baked into url.path, bypassing + # redact_query; they must now land in url.query and be redacted there. + it 'redacts secret caller query params and keeps them out of url.path' do + + stubs = Faraday::Adapter::Test::Stubs.new { |s| s.get(%r{/x}) { [200, {}, '{}'] } } + logger, io = recorder + build(stubs, logger: logger).make_request(:get, '/x', query_params: { token: 'CALLERTOKEN', user_id: 'u1' }) + sent = io.string.lines.find { |l| l.include?('http.request.sent') } + expect(sent).to include('url.path=/x url.query=') + expect(sent).to include('token=').and include('user_id=u1').and include('api_key=') + expect(io.string).not_to include('CALLERTOKEN') + + end + + it 'redacts secrets in a caller-built path' do + + stubs = Faraday::Adapter::Test::Stubs.new { |s| s.post(%r{/x}) { [200, {}, '{}'] } } + logger, io = recorder + build(stubs, logger: logger).post('/x?token=PATHTOKEN') + expect(io.string).to include('url.path=/x?token=') + expect(io.string).not_to include('PATHTOKEN') + + end + + it 'never logs the Authorization header or the JWT' do + + stubs = Faraday::Adapter::Test::Stubs.new { |s| s.get(%r{/x}) { [200, {}, '{}'] } } + logger, io = recorder + build(stubs, logger: logger, log_bodies: true).make_request(:get, '/x') + expect(io.string).not_to match(/authorization/i) + expect(io.string).not_to include('eyJ') + expect(io.string).not_to include('sekret') + + end + + # SEC-2535: CR/LF (and other control characters) in any logged value must + # not be able to forge extra log lines. + it 'escapes CR/LF in path, query, bodies and error messages' do + + forged = "\r\nI, [2026-01-01] INFO -- : forged" + stubs = Faraday::Adapter::Test::Stubs.new do |s| + + s.post(%r{/ok}) { [200, { 'Content-Type' => 'text/plain' }, "body#{forged}"] } + s.get(%r{/boom}) { raise Faraday::ConnectionFailed, "refused#{forged}" } + + end + logger, io = recorder + client = build(stubs, logger: logger, log_bodies: true) + client.make_request(:post, '/ok', query_params: { user_id: "u1#{forged}" }, body: { text: "hi#{forged}" }) + expect { client.make_request(:get, '/boom') }.to raise_error(GetStreamRuby::TransportError) + # Generated clients interpolate path params unencoded; the URI parser + # rejects CR/LF, but only after http.request.sent was already logged. + expect { client.make_request(:get, "/ok/c1#{forged}") }.to raise_error(URI::InvalidURIError) + + expect(io.string.lines.grep(/forged/).size).to eq(io.string.lines.grep(/forged/).uniq.size) + expect(io.string.lines).to all(satisfy { |l| !l.start_with?('I, [2026-01-01]') }) + expect(io.string).to include('/ok/c1\\r\\nI, [2026-01-01]') + expect(io.string).to include('user_id=u1\\r\\nI') + expect(io.string).to include('http.response.body=body\\r\\nI') + expect(io.string).to include('error.message=refused\\r\\nI') + + end + + it 'sanitize helper' do + + sanitize = GetStreamRuby::LogRedaction.method(:sanitize) + expect(sanitize.call("a\r\nb\tc\e[31md\u2028e\u0085f")).to eq('a\\r\\nb\\tc\\e[31md\\u2028e\\u0085f') + expect(sanitize.call("\xFF\n".b)).to eq("\uFFFD\\n") + expect(sanitize.call(nil)).to eq('') + expect(sanitize.call('plain ünïcode')).to eq('plain ünïcode') + + end + end