Class: Parse::Middleware::BodyBuilder
- Inherits:
-
Faraday::Middleware
- Object
- Faraday::Middleware
- Parse::Middleware::BodyBuilder
- Includes:
- Protocol
- Defined in:
- lib/parse/client/body_builder.rb
Overview
This middleware takes an incoming Parse response, after an outgoing request, and creates a Parse::Response object.
Constant Summary collapse
- HTTP_METHOD_OVERRIDE =
Header sent when a GET requests exceeds the limit.
"X-Http-Method-Override"- MAX_URL_LENGTH =
Maximum url length for most server requests before HTTP Method Override is used.
2_000.freeze
- SENSITIVE_FIELDS =
Fields that should be redacted from log output.
Covers MFA material (
recoverycodes and thesecretreturned by MFA enrollment, also underauthDataResponse) and the storage-form credential columns a raw MongoDB document carries (_session_token,_hashed_password, and the reset/verify tokens). Keys starting with SENSITIVE_KEY_PREFIXES (per-provider_auth_data_<provider>columns) are redacted too. %w[ password token sessionToken session_token access_token authData masterKey master_key apiKey api_key clientKey client_key javascriptKey javascript_key refreshToken refresh_token recovery recoveryCodes recovery_codes authDataResponse secret _session_token _hashed_password _email_verify_token _perishable_token _password_history ].freeze
- SENSITIVE_KEY_PREFIXES =
Key prefixes whose values are always redacted.
%w[_auth_data_].freeze
- SENSITIVE_VALUE =
A credential value: a double- or single-quoted string (with escapes), taken whole so a quoted value with spaces is redacted entirely, or an unquoted run up to a delimiter.
/(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[^"'&\s,}\]]+)/- SENSITIVE_PATTERN =
/(#{(SENSITIVE_FIELDS + SENSITIVE_KEY_PREFIXES.map { |p| "#{p}\\w+" }).join("|")})(["']?\s*[=:>]\s*)(#{SENSITIVE_VALUE.source})/i- SENSITIVE_HEADER_NAMES =
Credential header names whose value is redacted when they appear as text (
X-Parse-Master-Key: mk,Authorization: Bearer x), for example in an error message or a pasted request. Real request headers are redacted through REDACTED_HEADERS. %w[ X-Parse-Master-Key X-Parse-REST-API-Key X-Parse-Session-Token X-Parse-Javascript-Key X-Parse-Client-Key X-Parse-Webhook-Key Authorization ].freeze
- SENSITIVE_HEADER_PATTERN =
Header-shaped text: a credential header name, a
:or=separator, an optional auth scheme (Bearer,Basic,Token), then the value. /(#{SENSITIVE_HEADER_NAMES.map { |n| Regexp.escape(n) }.join("|")})(["']?\s*[=:]\s*)((?:bearer|basic|token)\s+)?(#{SENSITIVE_VALUE.source})/i- SENSITIVE_FIELDS_SET =
Lookup set of sensitive field names for structural (JSON) redaction — case-insensitive match on the key, not the value. Walks the parsed structure so nested objects like "password":{"nested":"value"} and escaped-quote payloads (which the regex misses) are scrubbed.
SENSITIVE_FIELDS.map(&:downcase).to_set.freeze
- REDACTED_PLACEHOLDER =
Placeholder used in place of redacted values.
"[FILTERED]"- LOG_VECTOR_COMPACT_THRESHOLD =
Minimum length at which a numeric-only Array in a logged JSON body is compacted to a single placeholder string instead of printed verbatim. Two concerns drive this:
- Noise. A 1536-float OpenAI embedding inlines as ~25 KB of
JSON per logged row. Aggregation pipelines with
$vectorSearch.queryVectorand any save/fetch carrying a:vectorfield would otherwise drown operator logs. - Sensitivity. Embeddings are reversible-by-similarity: an attacker who scrapes operator logs can reconstruct high-level features of the source text (topic, sentiment, sometimes near-verbatim phrases for short inputs) by nearest-neighbor lookup against a public model.
Threshold rationale: 32 is well below every common embedding width (BGE-small 384, Cohere 1024, OpenAI small 1536, OpenAI large 3072) and well above any normal Parse Array property (tags, role lists, etc.). Numeric-only check additionally protects normal long arrays of strings/objects.
- Noise. A 1536-float OpenAI embedding inlines as ~25 KB of
JSON per logged row. Aggregation pipelines with
32- REDACTED_HEADERS =
Request headers that must never be printed verbatim in debug logs. Matched case-insensitively against Faraday header keys.
[ Parse::Protocol::MASTER_KEY, Parse::Protocol::API_KEY, Parse::Protocol::SESSION_TOKEN, # Caller-supplied Cloud Code context (X-Parse-Cloud-Context) carries # `context.to_json`, which may hold PII / request metadata. Redact it in # the header log; the body/as_json log path scrubs sensitive sub-values # of context separately. Parse::Protocol::CLOUD_CONTEXT, "X-Parse-JavaScript-Key", "Authorization", "Cookie", # Embedding-provider credentials (Parse::Embeddings::OpenAI and # forthcoming Cohere/Voyage adapters). These never touch Parse # Server itself, but they share the same Faraday log path when a # caller mounts the embeddings connection through Parse logging. # OpenAI's official auth header is `Authorization: Bearer …` # (already covered above); Organization/Project are listed here # since they're account-identifying metadata operators may not # want to publish. `X-Api-Key` and `Anthropic-Api-Key` are # reserved for forthcoming non-OpenAI providers. "X-Api-Key", "OpenAI-Organization", "OpenAI-Project", "Anthropic-Api-Key", # Cohere, Voyage, Jina, and DashScope (Qwen) use Bearer auth # (covered by "Authorization" above), but some operators front # them with a proxy that rewrites to a vendor-specific header. # These are listed defensively so a future header-form switch # doesn't silently leak keys into Faraday logs. `Api-Key` is the # bare form some vendor SDKs and proxies use; covered for parity. "Cohere-Api-Key", "Voyage-Api-Key", "Jina-Api-Key", "Api-Key", "X-DashScope-Api-Key", "DashScope-Api-Key", ].map(&:downcase).freeze
Constants included from Protocol
Protocol::API_KEY, Protocol::APP_ID, Protocol::CLOUD_CONTEXT, Protocol::CONTENT_TYPE, Protocol::CONTENT_TYPE_FORMAT, Protocol::EMAIL, Protocol::INSTALLATION_ID, Protocol::MASTER_KEY, Protocol::PASSWORD, Protocol::READ_PREFERENCE, Protocol::READ_PREFERENCES, Protocol::REVOCABLE_SESSION, Protocol::SERVER_URL, Protocol::SESSION_TOKEN
Class Attribute Summary collapse
-
.logging ⇒ Boolean
Allows logging.
Class Method Summary collapse
-
.redact(str) ⇒ String
Redacts sensitive fields from a string for safe logging.
-
.redact_patterns(str) ⇒ String
The regex pass of BodyBuilder.redact on its own: replaces values that follow a credential field name (
password=x,"sessionToken":"r:x") or a credential header name (X-Parse-Master-Key: mk,Authorization: Bearer x). -
.redact_string_values!(obj) ⇒ Object
Apply BodyBuilder.redact_patterns to every String value in a parsed JSON structure, in place.
Class Attribute Details
.logging ⇒ Boolean
Allows logging. Set to true to enable logging, false to disable.
You may specify :debug for additional verbosity.
146 147 148 |
# File 'lib/parse/client/body_builder.rb', line 146 def logging @logging end |
Class Method Details
.redact(str) ⇒ String
Redacts sensitive fields from a string for safe logging.
Two passes run in sequence so that no payload shape leaks secrets:
Structural pass. If the body (after whitespace trim) parses as JSON, the parsed structure is walked recursively. Any value whose key matches
SENSITIVE_FIELDS_SET(case-insensitive) is replaced. String values that themselves look like JSON are recursively parsed and scrubbed — catches{"body":"{\"password\":\"x\"}"}payloads.Regex pass. The result of the structural pass (or the original string if parsing failed) is always also run through the
SENSITIVE_PATTERNregex as defense-in-depth. This catches form- encoded bodies, partial JSON, escaped-quote payloads, and string array elements like["password=hunter2"]that the structural walker can't redact in-place.
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 |
# File 'lib/parse/client/body_builder.rb', line 168 def self.redact(str) s = str.to_s return s if s.empty? if (parsed = try_parse_json(s)) scrubbed = scrub_sensitive!(parsed) compact_vectors!(scrubbed) begin # Text patterns run on each string value before encoding, never # on the encoded JSON: escaped quotes inside a value # (`password=\"x\"`) would defeat them and could corrupt the JSON. return redact_string_values!(scrubbed).to_json rescue StandardError # Fall through to the text pass on the original string. end end redact_patterns(s) end |
.redact_patterns(str) ⇒ String
The regex pass of redact on its own: replaces values that follow
a credential field name (password=x, "sessionToken":"r:x") or a
credential header name (X-Parse-Master-Key: mk,
Authorization: Bearer x). Use it on text that is not JSON, or on
JSON that has already been scrubbed structurally.
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 |
# File 'lib/parse/client/body_builder.rb', line 208 def self.redact_patterns(str) s = str.to_s return s if s.empty? s = s.gsub(SENSITIVE_PATTERN) do key_part = $1 sep_part = $2 val_part = $3 # Skip values that the structural pass already redacted. The # value class `[^"&\s,}\]]+` stops at the bracket, so without # this a second pass would turn `"[FILTERED]"` into # `[FILTERED]]`. "#{key_part}#{sep_part}#{redacted_value(val_part)}" end s.gsub(SENSITIVE_HEADER_PATTERN) do name_part = $1 sep_part = $2 scheme_part = $3 val_part = $4 "#{name_part}#{sep_part}#{scheme_part}#{redacted_value(val_part)}" end end |
.redact_string_values!(obj) ⇒ Object
Apply redact_patterns to every String value in a parsed JSON structure, in place. Keys are left alone (the structural pass already replaced the values of sensitive keys).
191 192 193 194 195 196 197 198 199 |
# File 'lib/parse/client/body_builder.rb', line 191 def self.redact_string_values!(obj) case obj when Hash obj.each { |k, v| obj[k] = v.is_a?(String) ? redact_patterns(v) : redact_string_values!(v) } when Array obj.map! { |v| v.is_a?(String) ? redact_patterns(v) : redact_string_values!(v) } end obj end |