RedactJSONSecrets redacts sensitive JSON values by key name. When the input is not valid JSON (truncated body, HTML error page, etc.) the raw bytes are replaced entirely with a diagnostic placeholder to avoid leaking credentials from malformed payloads.
(data []byte)
| 93 | // the raw bytes are replaced entirely with a diagnostic placeholder |
| 94 | // to avoid leaking credentials from malformed payloads. |
| 95 | func RedactJSONSecrets(data []byte) []byte { |
| 96 | if len(data) == 0 { |
| 97 | return data |
| 98 | } |
| 99 | |
| 100 | decoder := json.NewDecoder(bytes.NewReader(data)) |
| 101 | decoder.UseNumber() |
| 102 | |
| 103 | var value any |
| 104 | if err := decoder.Decode(&value); err != nil { |
| 105 | // Cannot parse: replace entirely to prevent credential leaks |
| 106 | // from non-JSON error responses (HTML pages, partial bodies). |
| 107 | return []byte(`{"error":"chatdebug: body is not valid JSON, redacted for safety"}`) |
| 108 | } |
| 109 | if err := consumeJSONEOF(decoder); err != nil { |
| 110 | return []byte(`{"error":"chatdebug: body contains extra JSON values, redacted for safety"}`) |
| 111 | } |
| 112 | |
| 113 | redacted, changed := redactJSONValue(value) |
| 114 | if !changed { |
| 115 | return data |
| 116 | } |
| 117 | |
| 118 | encoded, err := json.Marshal(redacted) |
| 119 | if err != nil { |
| 120 | return data |
| 121 | } |
| 122 | return encoded |
| 123 | } |
| 124 | |
| 125 | // RedactNDJSONSecrets redacts sensitive values in newline-delimited |
| 126 | // JSON (NDJSON) payloads. Each non-empty line is treated as an |