coolhand 0.10.0 → 0.11.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,111 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Coolhand
4
+ # Redacts credential-bearing values from request and response bodies before they are sent to
5
+ # Coolhand. Header and URL redaction live in BaseInterceptor; this covers the body.
6
+ module BodyRedactor
7
+ module_function
8
+
9
+ # Body keys whose *string* value is a credential in any request or response body, matched
10
+ # exactly (never as a substring) against the key lowercased with `_`, `-` and spaces removed,
11
+ # so `api_key`, `apiKey`, `API-Key` and `apikey` all match. Only String leaves are redacted:
12
+ # a JSON Schema property named `api_key` has a Hash value and is left alone, as is a numeric
13
+ # `usage.total_tokens`. Covers OpenAI Responses/Realtime MCP `tools[].authorization`, Anthropic
14
+ # `mcp_servers[].authorization_token`, and the legacy Realtime `client_secret` string form. Also
15
+ # covers `x-api-key`, AWS `aws_secret_access_key`/`secret_access_key`, `session_token`,
16
+ # `bearer_token` and any String under a generic `secret` key.
17
+ CREDENTIAL_BODY_KEYS = %w[
18
+ authorization authorizationtoken accesstoken refreshtoken idtoken
19
+ apikey clientsecret privatekey secretkey password
20
+ xapikey secret secretaccesskey awssecretaccesskey sessiontoken bearertoken
21
+ ].freeze
22
+
23
+ # Body keys whose *string* value is a URL that can carry credentials (MCP `server_url`, a
24
+ # presigned `image_url`/`file_url`, a datastore `endpoint`). Matched exactly like
25
+ # CREDENTIAL_BODY_KEYS, but the value is scrubbed with BaseInterceptor.sanitize_url instead of
26
+ # replaced, and only when it is a single absolute URL: prose that merely contains one is never
27
+ # touched. A bare `token` key is deliberately absent from both lists (logprobs use `{"token":"Hello"}`).
28
+ URL_BODY_KEYS = %w[url serverurl imageurl fileurl endpoint].freeze
29
+
30
+ def redact(body)
31
+ return StringBodyRedactor.redact(body) if body.is_a?(String)
32
+ return body unless body.is_a?(Hash) || body.is_a?(Array)
33
+
34
+ redact_body_node(body, 0)
35
+ end
36
+
37
+ def redact_body_node(node, depth, secret_object: false)
38
+ return BaseInterceptor::REDACTED if depth > BaseInterceptor::MAX_BODY_DEPTH
39
+
40
+ case node
41
+ when Hash then redact_body_hash(node, depth, secret_object: secret_object)
42
+ when Array then node.map { |v| redact_body_node(v, depth + 1) }
43
+ else node
44
+ end
45
+ end
46
+
47
+ # `secret_object` marks the object under a `client_secret` key (legacy Realtime
48
+ # `{value, expires_at}`), whose `value` is the ephemeral key.
49
+ def redact_body_hash(hash, depth, secret_object: false)
50
+ context = { secret_value: secret_object || ephemeral_secret?(hash), mcp: mcp_tool?(hash) }
51
+ hash.each_with_object({}) do |(key, value), acc|
52
+ acc[key] = redact_body_entry(normalize_body_key(key), value, depth, context)
53
+ end
54
+ end
55
+
56
+ def redact_body_entry(name, value, depth, context)
57
+ if name == "datasources"
58
+ BaseInterceptor.redact_sensitive_body_values(value, depth + 1)
59
+ elsif value.is_a?(String)
60
+ redact_string_value(name, value, context)
61
+ elsif name == "headers" && context[:mcp]
62
+ redact_header_values(value, depth + 1)
63
+ elsif name == "clientsecret" && value.is_a?(Hash)
64
+ redact_body_node(value, depth + 1, secret_object: true)
65
+ else
66
+ redact_body_node(value, depth + 1)
67
+ end
68
+ end
69
+
70
+ def redact_string_value(name, value, context)
71
+ return BaseInterceptor::REDACTED if redact_string_leaf?(name, context)
72
+
73
+ URL_BODY_KEYS.include?(name) ? BaseInterceptor.redact_embedded_url_credentials(value) : value
74
+ end
75
+
76
+ def redact_string_leaf?(name, context)
77
+ CREDENTIAL_BODY_KEYS.include?(name) || (context[:secret_value] && name == "value")
78
+ end
79
+
80
+ def normalize_body_key(key)
81
+ key.to_s.delete("_ -").downcase # trailing "-" is a literal hyphen, not a range
82
+ end
83
+
84
+ # Realtime GA `POST /v1/realtime/client_secrets` returns `{"value": "ek_...", "expires_at": 123,
85
+ # "session": {...}}`. `value` alone is far too generic to redact by name, so require the
86
+ # numeric `expires_at` that accompanies it.
87
+ def ephemeral_secret?(hash)
88
+ hash_value(hash, "value").is_a?(String) && hash_value(hash, "expires_at").is_a?(Numeric)
89
+ end
90
+
91
+ # An OpenAI remote-MCP tool (`type: "mcp"`, or any entry carrying a `server_url`), whose
92
+ # `headers` map holds authentication headers. A bare `headers` key elsewhere is left alone.
93
+ def mcp_tool?(hash)
94
+ hash_value(hash, "type") == "mcp" || !hash_value(hash, "server_url").nil?
95
+ end
96
+
97
+ # String values are the credentials; anything else (a malformed nested shape) goes back through
98
+ # the generic walk so it is still depth-limited and credential-key checked.
99
+ def redact_header_values(headers, depth)
100
+ return redact_body_node(headers, depth) unless headers.is_a?(Hash)
101
+
102
+ headers.transform_values do |v|
103
+ v.is_a?(String) ? BaseInterceptor::REDACTED : redact_body_node(v, depth + 1)
104
+ end
105
+ end
106
+
107
+ def hash_value(hash, name)
108
+ hash.fetch(name) { hash[name.to_sym] }
109
+ end
110
+ end
111
+ end
@@ -0,0 +1,121 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Coolhand
4
+ module NetHttpInterceptor
5
+ # Stands in for a request's body_stream while Net::HTTP sends it, copying the bytes that pass
6
+ # through into a buffer capped at max_captured_body_bytes. The host's stream is read exactly
7
+ # once, by Net::HTTP, in the same chunks as without the gem; nothing is read ahead, buffered in
8
+ # full or rewound. Past the cap the buffer is dropped and only a byte count is kept, so memory
9
+ # stays bounded however large the upload is.
10
+ #
11
+ # Deliberately exposes nothing but #read (and #readpartial, only when the source has it): a
12
+ # delegating wrapper would also expose #to_io/#to_path, which IO.copy_stream uses to read the
13
+ # underlying file directly, bypassing the tap.
14
+ class BodyStreamTap
15
+ attr_reader :source, :bytes_seen
16
+
17
+ # IO.copy_stream also accepts a path (String) or a Pathname as its source, reading the file
18
+ # itself; the tap only offers #read, which those don't support, so they are left untouched.
19
+ def self.tappable?(stream)
20
+ stream.respond_to?(:read) && !stream.is_a?(String) &&
21
+ (stream.respond_to?(:to_io) || !stream.respond_to?(:to_path))
22
+ end
23
+
24
+ def self.install(req)
25
+ tap = new(req.body_stream)
26
+ req.body_stream = tap
27
+ tap
28
+ end
29
+
30
+ def initialize(source)
31
+ @source = source
32
+ @buffer = +"".b
33
+ @bytes_seen = 0
34
+ @eof = false
35
+ @failed = false
36
+ define_singleton_method(:readpartial) { |*args| read_partial(*args) } if source.respond_to?(:readpartial)
37
+ end
38
+
39
+ def read(*args)
40
+ data = @source.read(*args)
41
+ record(data, finished: end_of_stream?(args, data))
42
+ data
43
+ end
44
+
45
+ # Whether the source has been read to its end (not IO#eof?: false until a read hits the end).
46
+ def reached_end?
47
+ @eof
48
+ end
49
+
50
+ # The capture itself failed (not the host's stream); the request body is simply not logged.
51
+ def failed?
52
+ @failed
53
+ end
54
+
55
+ def overflowed?
56
+ @buffer.nil? && !@failed
57
+ end
58
+
59
+ def body
60
+ @buffer&.dup&.force_encoding(Encoding::UTF_8)
61
+ end
62
+
63
+ # Puts the host's own stream back, unless something else has replaced the tap since.
64
+ def restore_stream(req)
65
+ req.body_stream = @source if req.body_stream.equal?(self)
66
+ end
67
+
68
+ # The request body for the log once the request has been attempted. Over the cap is known
69
+ # from the bytes seen so far, even if the stream was not fully sent. Otherwise a stream that
70
+ # never reached its end (the request failed first) has no complete body.
71
+ def body_for_log(req)
72
+ return if failed?
73
+ return helpers.body_too_large_marker(req, bytes_seen) if overflowed?
74
+ return incomplete_marker(req) unless reached_end?
75
+
76
+ BaseInterceptor.parse_json(body)
77
+ end
78
+
79
+ private
80
+
81
+ # Reading everything, or getting nothing back from a read for a positive length (IO.copy_stream
82
+ # also treats an empty String there as the end).
83
+ def end_of_stream?(args, data)
84
+ length = args.first
85
+ length.nil? || data.nil? || (length.positive? && data.empty?)
86
+ end
87
+
88
+ def helpers
89
+ NetHttpInterceptor::Helpers
90
+ end
91
+
92
+ def incomplete_marker(req)
93
+ helpers.skipped_capture_marker(req, "body_stream_incomplete", size_bytes: bytes_seen)
94
+ end
95
+
96
+ def read_partial(*args)
97
+ data = @source.readpartial(*args)
98
+ record(data)
99
+ data
100
+ rescue EOFError
101
+ @eof = true
102
+ raise
103
+ end
104
+
105
+ # Runs inside the host's request send: whatever goes wrong here must never reach the host.
106
+ def record(data, finished: false)
107
+ @eof ||= finished
108
+ return unless data.is_a?(String)
109
+
110
+ @bytes_seen += data.bytesize
111
+ return unless @buffer
112
+
113
+ @buffer = helpers.over_capture_limit?(@bytes_seen) ? nil : @buffer << data.b
114
+ rescue StandardError => e
115
+ @failed = true
116
+ @buffer = nil
117
+ Coolhand.log "❌ Error capturing request body_stream: #{e.message}"
118
+ end
119
+ end
120
+ end
121
+ end
@@ -8,7 +8,8 @@
8
8
  # Users can disable: c.exclude_api_patterns = []
9
9
 
10
10
  - "/batchPredictionJobs/"
11
- # Azure OpenAI control-plane paths (not inference) — both spellings are needed
11
+ # OpenAI-compatible control-plane paths (not inference), on Azure OpenAI Service
12
+ # and Amazon Bedrock alike — both spellings are needed
12
13
  # since substring matching is contiguous: "/openai/files" does not match
13
14
  # "/openai/v1/files".
14
15
  - "/openai/files"
@@ -23,7 +23,16 @@
23
23
  - "models.inference.ai.azure.com"
24
24
  - "aiplatform.googleapis.com"
25
25
  - "gateway.ai.cloudflare.com"
26
+ # Amazon Bedrock. Every endpoint variant needs its own entry: a wildcard entry is
27
+ # an exact host match with no implicit subdomains, and "amazonaws.com.cn" is not a
28
+ # dot-boundary suffix of "amazonaws.com". "api.aws" hosts are the dual-stack (IPv6)
29
+ # endpoints; "-fips" hosts are the FIPS 140-3 ones, used by GovCloud and other
30
+ # FIPS-constrained callers (they exist in commercial regions too).
26
31
  - "bedrock-runtime.*.amazonaws.com"
32
+ - "bedrock-runtime.*.amazonaws.com.cn"
33
+ - "bedrock-runtime-fips.*.amazonaws.com"
34
+ - "bedrock-runtime.*.api.aws"
35
+ - "bedrock-runtime-fips.*.api.aws"
27
36
  - "api.deepseek.com"
28
37
  - "api.mistral.ai"
29
38
  - "api.perplexity.ai"
@@ -15,7 +15,7 @@ module Coolhand
15
15
  # Unlike every other service this one needs no API key. A configured `api_key` is sent as `X-API-Key` and lifts
16
16
  # the anonymous limit of 30 requests per minute per IP (429 beyond); with none, no key header is sent. A key the
17
17
  # server rejects raises a 401 {Coolhand::HttpError}; it is not retried anonymously. See docs/help-center.md.
18
- class PublicContentService < ApiService
18
+ class HelpCenterService < ApiService
19
19
  include ReadQuery
20
20
 
21
21
  ERROR_NOUN = "Help center"
@@ -14,6 +14,7 @@ module Coolhand
14
14
  include ReadQuery
15
15
 
16
16
  ERROR_NOUN = "Log"
17
+ FAILURE_SUMMARY_PATH = "failure_summary"
17
18
  BLANK_ID_MESSAGE = "get_log: id must be a non-empty log hashid"
18
19
 
19
20
  def initialize
@@ -22,14 +23,15 @@ module Coolhand
22
23
 
23
24
  # Filters, cost ordering, error semantics and server behaviour: docs/log-search.md.
24
25
  def search_logs(template_id: nil, workload_id: nil, system_prompt_contains: nil, user_prompt_contains: nil,
25
- model: nil, source_api: nil, source_api_result: nil, source_application: nil, project_path: nil,
26
- unmatched_only: nil, days_back: nil, since: nil, until: nil, min_cost: nil, order: nil,
26
+ error_contains: nil, model: nil, source_api: nil, source_api_result: nil, source_application: nil,
27
+ project_path: nil, unmatched_only: nil, days_back: nil, since: nil, until: nil, min_cost: nil, order: nil,
27
28
  include_prompts: nil, include_total: nil, sort: nil, page: nil, per: nil)
28
29
  query = {
29
30
  template_id: template_id,
30
31
  workload_id: workload_id,
31
32
  system_prompt_contains: system_prompt_contains,
32
33
  user_prompt_contains: user_prompt_contains,
34
+ error_contains: error_contains,
33
35
  model: model,
34
36
  source_api: source_api,
35
37
  source_api_result: source_api_result,
@@ -50,11 +52,21 @@ module Coolhand
50
52
  fetch_list(query, LogSearchResult, :logs, page: page, per: per)
51
53
  end
52
54
 
55
+ # Failed requests rolled up by error pattern and by template. One object, not paginated. Pass a
56
+ # pattern's `:error_pattern` as `search_logs(error_contains:)` to list its logs. `days_back` is sent
57
+ # as given, so the server answers 422 for zero or negative. docs/log-search.md.
58
+ def failure_summary(days_back: nil)
59
+ get_json(action_url(FAILURE_SUMMARY_PATH, { days_back: days_back }.compact), ERROR_NOUN)
60
+ end
61
+
53
62
  # The full log, with `cost` and `cost_breakdown`. Both are nil when the log has no tokens or its
54
63
  # model has no pricing.
55
- def get_log(id, section: nil, max_chars: nil, search_query: nil, include_thinking: nil)
64
+ # `turn_metrics` is added only when `include_turn_metrics: true`; it is nil for a log that is not a
65
+ # captured agent session.
66
+ def get_log(id, section: nil, max_chars: nil, search_query: nil, include_thinking: nil,
67
+ include_turn_metrics: nil)
56
68
  query = { section: section, max_chars: max_chars, search_query: search_query,
57
- include_thinking: include_thinking }.compact
69
+ include_thinking: include_thinking, include_turn_metrics: include_turn_metrics }.compact
58
70
  get_json(resource_url(id, BLANK_ID_MESSAGE, query), ERROR_NOUN)
59
71
  end
60
72
  end
@@ -4,6 +4,25 @@ require_relative "api_service"
4
4
 
5
5
  module Coolhand
6
6
  class LoggerService < ApiService
7
+ # CGI/Rack/Rails/app-server variables that show up in a Rails `request.headers` iteration
8
+ # (it walks the whole Rack env) but are not HTTP headers. CONTENT_TYPE and
9
+ # CONTENT_LENGTH are real headers and are deliberately absent. ORIGINAL_FULLPATH and
10
+ # REQUEST_PATH carry the query string, so they must never be forwarded. HTTP_PROXY is the
11
+ # process env var (it may embed credentials), never a client header (the "httpoxy" case).
12
+ RACK_ENV_CGI_KEYS = %w[
13
+ AUTH_TYPE GATEWAY_INTERFACE HTTPS HTTP_PROXY HTTP_VERSION ORIGINAL_FULLPATH ORIGINAL_SCRIPT_NAME
14
+ PATH_INFO PATH_TRANSLATED QUERY_STRING REMOTE_ADDR REMOTE_HOST REMOTE_IDENT REMOTE_PORT
15
+ REMOTE_USER REQUEST_METHOD REQUEST_PATH REQUEST_URI SCRIPT_NAME SERVER_ADDR SERVER_NAME
16
+ SERVER_PORT SERVER_PROTOCOL SERVER_SOFTWARE
17
+ ].freeze
18
+
19
+ # CGI-style env key: uppercase letters, digits and underscores (REQUEST_METHOD, DATABASE_URL).
20
+ CGI_ENV_KEY_PATTERN = /\A[A-Z0-9_]+\z/
21
+ # Lowercase dotted Rack/Rails/server key: rack.session, action_dispatch.request.parameters, puma.config.
22
+ RACK_DOTTED_KEY_PATTERN = /\A[a-z0-9_]+(?:\.[a-z0-9_]+)+\z/
23
+ RACK_ENV_HEADER_KEYS = %w[CONTENT_TYPE CONTENT_LENGTH].freeze
24
+ private_constant :CGI_ENV_KEY_PATTERN, :RACK_DOTTED_KEY_PATTERN, :RACK_ENV_HEADER_KEYS
25
+
7
26
  def initialize
8
27
  super("v2/llm_request_logs")
9
28
  end
@@ -26,8 +45,8 @@ module Coolhand
26
45
  method: options[:method] || "POST",
27
46
  url: BaseInterceptor.sanitize_url(options[:url] || build_webhook_url(source, event_type)),
28
47
  headers: sanitize_headers(headers),
29
- request_body: clean_webhook_body(webhook_body, source),
30
- response_body: options[:response_body],
48
+ request_body: BodyRedactor.redact(clean_webhook_body(webhook_body, source)),
49
+ response_body: BodyRedactor.redact(options[:response_body]),
31
50
  response_headers: options[:response_headers] && sanitize_headers(options[:response_headers]),
32
51
  status_code: options[:status_code] || 200,
33
52
  source: "#{source}_webhook"
@@ -58,21 +77,51 @@ module Coolhand
58
77
  return {} unless headers.respond_to?(:each)
59
78
 
60
79
  # Handle Rails request headers or plain hash
80
+ entries = headers.enum_for(:each).to_a
81
+ rack_env = rack_env_shaped?(entries)
82
+
61
83
  clean_headers = {}
62
- headers.each do |key, value|
63
- next unless key && value
84
+ entries.each do |key, value|
85
+ next unless forwardable_header?(key, value, rack_env: rack_env)
64
86
 
65
87
  # Convert Rails HTTP_ prefix headers
66
88
  clean_key = key.to_s.gsub(/^HTTP_/, "").tr("_", "-").downcase
67
89
 
68
90
  # Redact sensitive headers (shared with BaseInterceptor so both logging
69
91
  # paths treat the same header names as sensitive)
70
- clean_value = clean_key.match?(BaseInterceptor::SENSITIVE_HEADER_PATTERN) ? "[REDACTED]" : value.to_s
92
+ clean_value = BaseInterceptor.sensitive_header?(clean_key) ? "[REDACTED]" : value.to_s
71
93
  clean_headers[clean_key] = clean_value
72
94
  end
73
95
  clean_headers
74
96
  end
75
97
 
98
+ # Rails' request.headers#each yields the whole Rack env, not just headers. Drop the
99
+ # non-header entries (rack.session, action_dispatch.*, REQUEST_METHOD, QUERY_STRING, ...)
100
+ # so session/params data is never forwarded. Ordinary header names (including normalized
101
+ # plain-Hash ones like "Content-Type" or "x-webhook-id") never match the denylist.
102
+ # CGI/FastCGI handlers also put the process env (DATABASE_URL, REDIS_URL, ...) in the Rack
103
+ # env, so once the input looks like one, only HTTP_*, CONTENT_TYPE and CONTENT_LENGTH pass
104
+ # (a process env var that itself starts with HTTP_ still gets through; HTTP_PROXY is denied).
105
+ def forwardable_header?(key, value, rack_env: false)
106
+ return false unless key && value
107
+
108
+ name = key.to_s
109
+ return false if name.include?(".") || RACK_ENV_CGI_KEYS.include?(name)
110
+
111
+ !rack_env || name.start_with?("HTTP_") || RACK_ENV_HEADER_KEYS.include?(name)
112
+ end
113
+
114
+ # A Rack env is recognised by a positive signal the Rack spec guarantees (REQUEST_METHOD, or
115
+ # a lowercase dotted key like rack.input), or by every key being env-shaped. Requiring only
116
+ # the latter would let a single lowercase key (Warden's "warden", a shell's http_proxy)
117
+ # switch the allowlist off for the whole env. Mixed-case dotted names ("X.Trace") are
118
+ # valid header names, so they are not a signal.
119
+ def rack_env_shaped?(entries)
120
+ keys = entries.filter_map { |key, _value| key&.to_s }
121
+ keys.any? { |name| name == "REQUEST_METHOD" || name.match?(RACK_DOTTED_KEY_PATTERN) } ||
122
+ (keys.any? && keys.all? { |name| name.match?(CGI_ENV_KEY_PATTERN) })
123
+ end
124
+
76
125
  def clean_webhook_body(body, source)
77
126
  # Service-specific binary field filters
78
127
  binary_fields = case source.to_s.downcase