# How to dump requests in debug mode without leaking secrets

> Put one switch in front of a full request and response dump, mask credentials by name and by value, and grep the dump for the real tokens to prove none got through.

Source: https://voxgig.com/howto/dump-requests-in-debug-mode-without-leaking-secrets

- Audience: library-maintainer
- Level: intermediate
- Languages: typescript, python, go
- Verified: 2026-11-20
- Published: 2026-11-20

## Short answer

Gate the dump behind one environment variable and send every line through one redactor. In an sdkgen SDK, activate the debug feature in the constructor for headers, status, and timing, and pass a dumping system.fetch for URLs and bodies. Mask by header name, by the name of each parameter, and by value pattern, because signed URLs and token exchanges carry secrets no header rule sees. Then grep the dump for each real token and expect none.

---
## You will need

Node 22 or later, an SDK or HTTP client you control, and the values of the credentials it sends,
so a test can search for them. Verified 2026-11-20 against Node 22.23.5,
`@voxgig/create-sdkgen` 0.31.9, `@voxgig/sdkgen` 4.44.3, OpenAPI Generator 7.27.0, orval 8.48.0,
Go 1.24.7, and Python 3.13.18. The Go and Python demos use their standard libraries alone, and
every demo talks to a stand-in server on `127.0.0.1` that holds six canary secrets.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [Go `httputil.DumpRequestOut`](https://pkg.go.dev/net/http/httputil#DumpRequestOut) | A Go client whose `http.Client` transport you can set | It prints every header and the body verbatim, so the redaction is code you write | The client is not Go |
| [mitmproxy](https://docs.mitmproxy.org/stable/concepts/modes/#reverse-proxy) | You cannot change the client, or the client is a binary | Its CA installed on the client, or the client pointed at a reverse proxy, and no production traffic through it | The failure happens only in production |
| [OpenAPI Generator `Configuration.Debug`](https://github.com/OpenAPITools/openapi-generator/blob/master/modules/openapi-generator/src/main/resources/go/client.mustache) | Its Go or Python client, on your own machine | The Go and Python switches print tokens, cookies, and bodies with nothing masked | Anyone else can read the log |
| [orval `mutator`](https://orval.dev/docs/guides/custom-client/) | orval generates the client, and every call can pass through one function | The generated client has no debug option, so the switch, the dump, and the redaction are yours | You want the generator to own the switch |
| [sdkgen debug feature](https://github.com/voxgig/sdkgen/blob/main/docs/reference/features.md) | sdkgen generates the SDK, and headers, status, and timing are enough | It records the path template without the query, no bodies, and no `direct()` calls | You need bodies or full URLs, so add a dumping `system.fetch` |
| [undici `diagnostics_channel`](https://github.com/nodejs/undici/blob/main/docs/docs/api/DiagnosticsChannel.md) | Node's fetch, with no change to the client code | Raw method, path, and headers, masked only if your subscriber masks them | You need request bodies from the undici bundled with Node 22 |

Voxgig maintains sdkgen. It is one of six options here, not the recommendation.

The runtime hooks cost no code and mask nothing, so they suit a laptop and not a shared log.
The generators split three ways. sdkgen masks what it records but records less than a dump needs.
OpenAPI Generator's switch records everything and masks none of it, and orval leaves the whole
job to your `mutator` function. mitmproxy sees everything without a code change, which is also why its
capture needs guarding.

## Generate the SDK with the debug feature

Scaffold the project with `--feature debug`, generate, and compile. The page's sample commits the
compiled output under `generated/`.

```bash title="generate.sh"
npx --yes @voxgig/create-sdkgen@0.31.9 exports --def api.json --target ts --feature debug
(cd exports-sdk/.sdk && npm run generate)
(cd exports-sdk/ts && npm install --no-audit --no-fund && npm run build)
```

The [feature reference](https://github.com/voxgig/sdkgen/blob/main/docs/reference/features.md)
gives `active` a default of `false`, so the generated SDK records nothing until a constructor
switches it on. Its `redact` option masks `authorization`, `cookie`, `set-cookie`, `x-api-key`, and
three other header names by default.

## Switch it on from one environment variable

One variable controls the mode. `EXPORTS_DEBUG=1` activates the feature and prints each entry
through `onEntry`; unset, the constructor passes `active: false`.

```js title="client.mjs"
// The debug switch: EXPORTS_DEBUG=1 turns on sdkgen's debug feature, and
// EXPORTS_DEBUG=wire adds the full request and response dump as well.
export function makeClient({ base, apikey, env = process.env, log = console.error, now, secrets = [] }) {
  const mode = env.EXPORTS_DEBUG ?? ''
  const options = {
    base,
    apikey,
    feature: {
      debug: { active: mode !== '', onEntry: (e) => log(`debug ${JSON.stringify(e)}`), ...(now ? { now } : {}) },
    },
  }
  if (mode === 'wire') {
    const redact = makeRedactor({ values: [apikey, ...secrets] })
    options.system = { fetch: dumpingFetch({ redact, log, ...(now ? { now } : {}) }) }
  }
  return new ExportsSDK(options)
}
```

`demo.mjs` lists exports with a share token in the query, creates one, and exchanges a client
secret for an access token through `direct()`. It injects a clock that advances 4 ms per reading,
so the durations are stable.

```bash
EXPORTS_DEBUG=1 node demo.mjs
```

```text output
debug {"op":"export.list","method":"GET","url":"exports","headers":{"content-type":"application/json","accept":"application/json","authorization":"[redacted]"},"start":4,"status":200,"ok":true,"durationMs":4}
debug {"op":"export.create","method":"POST","url":"exports","headers":{"content-type":"application/json","accept":"application/json","authorization":"[redacted]"},"start":12,"status":201,"ok":true,"durationMs":4}
requests sent: 3, lines printed: 2
secrets found in the dump: none
```

The token reached the server as `Bearer tok_live_...`, and the entry shows `[redacted]`. Three
requests went out and two entries came back, because `direct()` bypasses the feature hooks. The
`url` field holds the path template, `exports`, so the share token is absent rather than masked.
No entry carries a body.

## Add URLs and bodies through system.fetch

The generated SDK sends every live request through `options.system.fetch`, a seam the feature
reference documents for replacing the client's transport. Pass a wrapper that prints each
exchange through the redactor and returns the response unread.

```js title="client.mjs"
// A fetch that prints each exchange through the redactor before returning
// the response untouched. sdkgen calls it as system.fetch(url, fetchdef).
export function dumpingFetch({ redact, log = console.error, now = () => performance.now(), fetch = globalThis.fetch }) {
  return async (url, def = {}) => {
    const start = now()
    const reqType = new Headers(def.headers ?? {}).get('content-type') ?? ''
    log(`> ${def.method ?? 'GET'} ${redact.url(url)}`)
    log(`> headers ${JSON.stringify(redact.headers(def.headers))}`)
    if (def.body) log(`> body ${redact.body(def.body, reqType)}`)
    const res = await fetch(url, def)
    const text = await res.clone().text()
    log(`< ${res.status} in ${Math.round(now() - start)}ms`)
    log(`< headers ${JSON.stringify(redact.headers(res.headers))}`)
    log(`< body ${redact.body(text, res.headers.get('content-type') ?? '')}`)
    return res
  }
}
```

```bash
EXPORTS_DEBUG=wire node demo.mjs
```

```text output
> GET http://127.0.0.1:43227/v1/exports?share_token=[redacted]
> headers {"content-type":"application/json","accept":"application/json","authorization":"[redacted]","user-agent":"Mozilla/5.0 (compatible; ExportsSDK/1.0)"}
< 200 in 4ms
< headers {"connection":"keep-alive","content-type":"application/json","keep-alive":"timeout=5","set-cookie":"[redacted]","transfer-encoding":"chunked"}
< body [{"id":"e1","name":"q3-ledger","status":"ready","download_url":"https://files.example.com/e1.csv?X-Amz-Expires=300&X-Amz-Signature=[redacted]"}]
debug {"op":"export.list","method":"GET","url":"exports","headers":{"content-type":"application/json","accept":"application/json","authorization":"[redacted]"},"start":4,"status":200,"ok":true,"durationMs":12}
> POST http://127.0.0.1:43227/v1/exports
> headers {"content-type":"application/json","accept":"application/json","authorization":"[redacted]","user-agent":"Mozilla/5.0 (compatible; ExportsSDK/1.0)"}
> body {"name":"q4-ledger"}
< 201 in 4ms
< headers {"connection":"keep-alive","content-type":"application/json","keep-alive":"timeout=5","transfer-encoding":"chunked"}
< body {"id":"e2","name":"q4-ledger","status":"queued"}
debug {"op":"export.create","method":"POST","url":"exports","headers":{"content-type":"application/json","accept":"application/json","authorization":"[redacted]"},"start":20,"status":201,"ok":true,"durationMs":12}
> POST http://127.0.0.1:43227/v1/oauth/token
> headers {"content-type":"application/x-www-form-urlencoded","accept":"application/json","authorization":"[redacted]","user-agent":"Mozilla/5.0 (compatible; ExportsSDK/1.0)"}
> body grant_type=client_credentials&client_id=reports&client_secret=[redacted]
< 200 in 4ms
< headers {"connection":"keep-alive","content-type":"application/json","keep-alive":"timeout=5","transfer-encoding":"chunked"}
< body {"access_token":"[redacted]","token_type":"[redacted]","expires_in":3600}
requests sent: 3, lines printed: 19
secrets found in the dump: none
```

Every secret is masked where it travels. That covers the share token in the URL, the cookie, and
the S3 signature inside the JSON body. It covers the client secret in the form body[^1] and the
access token in the response. `token_type` is masked too, because its name contains `token`.
Over-masking is the cheaper failure. The tests confirm the server still received each credential
the client sent.

## Mask by name and by value

The redactor in `redact.mjs` applies three rules to every header value, URL, and body. A name rule
covers headers, query parameters, and form and JSON fields. A value rule catches a scheme and its
credential, or a JWT, under any name.

```js title="redact.mjs"
// Header names whose whole value is a credential.
const SECRET_HEADERS = new Set([
  'authorization', 'proxy-authorization', 'cookie', 'set-cookie',
  'x-api-key', 'api-key', 'x-auth-token', 'x-amz-security-token',
])

// A field or parameter name is secret when, lower-cased with '-' and '_'
// removed, it contains one of these, or is exactly one of the short ones.
const SECRET_PARTS = ['token', 'secret', 'password', 'passwd', 'signature', 'apikey', 'credential', 'session', 'assertion']
const SECRET_EXACT = new Set(['key', 'sig', 'code', 'auth'])

export function secretName(name) {
  const n = String(name).toLowerCase().replace(/[-_]/g, '')
  return SECRET_EXACT.has(n) || SECRET_PARTS.some((p) => n.includes(p))
}

// Values that are secrets whatever they are called.
const VALUE_PATTERNS = [
  /\b(Bearer|Basic|Token)\s+[A-Za-z0-9._~+/=-]+/gi,  // a scheme and its credential
  /\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, // a JWT
]
```

Values the caller registers, such as the API token, are masked as written, percent-encoded and
base64-encoded. sdkgen's own [secret redaction](https://github.com/voxgig/sdkgen/blob/main/docs/explanation/secret-redaction.md)
takes the same approach with its value registry.

## See what the runtime hooks print

Node's fetch is undici, which publishes each request on
[`diagnostics_channel`](https://nodejs.org/api/diagnostics_channel.html). A subscriber needs no
change to the client, and it receives the raw headers.

```bash
node hooks.mjs
```

```text output
> GET /v1/exports?share_token=shr_q9t8r7e6w5x4 {"authorization":"Bearer tok_live_c0ffee4d2b19a7"}
< 200 {"content-type":"application/json","set-cookie":"session=sess_p0o9i8u7y6t5; HttpOnly; Path=/"}
> POST /v1/oauth/token {"content-type":"application/x-www-form-urlencoded"}
< 200 {"content-type":"application/json"}
exports listed: 1
secrets found in the dump: api token, share token in the query, session cookie
```

`node hooks.mjs --redact` runs the same subscriber through the redactor and finds none. undici
added channels for body chunks in 7.11.0, and Node 22.23.5 bundles undici 6.29.1, so a subscriber
here sees no body.

Python's equivalent is
[`set_debuglevel`](https://docs.python.org/3/library/http.client.html), which prints to stdout.[^2]

```bash
python3 debuglevel.py
```

```text output
send: b'GET /v1/exports?share_token=shr_q9t8r7e6w5x4 HTTP/1.1\r\nHost: 127.0.0.1:37411\r\nAccept-Encoding: identity\r\nAuthorization: Bearer tok_live_c0ffee4d2b19a7\r\n\r\n'
reply: 'HTTP/1.0 200 OK\r\n'
header: Content-Type: application/json
header: Content-Length: 33
header: Set-Cookie: session=sess_p0o9i8u7y6t5; HttpOnly
secrets found in the dump: api token, share token in the query, session cookie
```

## Dump the same calls from OpenAPI Generator and orval

OpenAPI Generator ships a debug switch with no redaction behind it. In its Python client,
`Configuration.debug` sets the class-wide `http.client` debug level that `set_debuglevel` sets on
one connection.

```python title="python-client/configuration.py"
        self.__debug = value
        if self.__debug:
            # if debug status is True, turn on debug logging
            for _, logger in self.logger.items():
                logger.setLevel(logging.DEBUG)
            # turn on httplib debug
            httplib.HTTPConnection.debuglevel = 1
        else:
            # if debug status is False, turn off debug logging,
            # setting log level to default `logging.WARNING`
            for _, logger in self.logger.items():
                logger.setLevel(logging.WARNING)
            # turn off httplib debug
            httplib.HTTPConnection.debuglevel = 0
```

The Go client's `Configuration.Debug` calls
[`httputil.DumpRequestOut`](https://pkg.go.dev/net/http/httputil#DumpRequestOut) and
`DumpResponse` before and after every call. `go/main.go` runs the generated client both ways:
with `Debug`, or with a redacting `RoundTripper` in `HTTPClient`.

```go title="go/main.go"
	log.SetOutput(&dump)

	cfg := exports.NewConfiguration()
	cfg.Servers = exports.ServerConfigurations{{URL: srv.URL + "/v1"}}
	cfg.UserAgent = "exports-debug-demo"
	switch mode {
	case "debug":
		cfg.Debug = true
	case "redact":
		cfg.HTTPClient = &http.Client{Transport: dumpTransport{next: http.DefaultTransport, log: func(s string) { log.Print(s) }}}
```

```bash
cd go && go run . debug
```

```text output
GET /v1/exports?share_token=shr_q9t8r7e6w5x4 HTTP/1.1
Host: 127.0.0.1:37115
User-Agent: exports-debug-demo
Accept: application/json
Authorization: Bearer tok_live_c0ffee4d2b19a7
Accept-Encoding: gzip



HTTP/1.1 200 OK
Content-Length: 156
Content-Type: application/json
Set-Cookie: session=sess_p0o9i8u7y6t5; HttpOnly; Path=/

[{"download_url":"https://files.example.com/e1.csv?X-Amz-Expires=300\u0026X-Amz-Signature=sig_s3k4j5h6g7f8","id":"e1","name":"q3-ledger","status":"ready"}]

exports listed: 1
secrets found in the dump: api token, share token in the query, S3 signature in a signed URL, session cookie
```

```bash
cd go && go run . redact
```

```text output
GET /v1/exports?share_token=[redacted] HTTP/1.1
Host: 127.0.0.1:43951
User-Agent: exports-debug-demo
Accept: application/json
Authorization: [redacted]
Accept-Encoding: gzip

HTTP/1.1 200 OK
Connection: close
Content-Type: application/json
Set-Cookie: [redacted]

[{"download_url":"https://files.example.com/e1.csv?X-Amz-Expires=300\u0026X-Amz-Signature=[redacted]","id":"e1","name":"q3-ledger","status":"ready"}]
exports listed: 1
secrets found in the dump: none
```

orval generates no debug option and no credential handling. Its documented lever is a
[`mutator`](https://orval.dev/docs/guides/custom-client/), a function every generated call goes
through, so the dump and the redaction live in `debugFetch`.

```js title="orval/orval.config.mjs"
export default {
  exports: {
    input: '../api.json',
    output: {
      target: './client/exports.ts',
      client: 'fetch',
      override: { mutator: { path: './debug-fetch.ts', name: 'debugFetch' } },
    },
  },
}
```

```bash
EXPORTS_DEBUG=1 node orval-demo.mjs
```

```text output
> GET http://127.0.0.1:40573/v1/exports?share_token=[redacted]
> headers {"authorization":"[redacted]"}
< 200 headers {"connection":"keep-alive","content-type":"application/json","keep-alive":"timeout=5","set-cookie":"[redacted]","transfer-encoding":"chunked"}
< body [{"id":"e1","name":"q3-ledger","status":"ready","download_url":"https://files.example.com/e1.csv?X-Amz-Expires=300&X-Amz-Signature=[redacted]"}]
> POST http://127.0.0.1:40573/v1/exports
> headers {"content-type":"application/json","authorization":"[redacted]"}
> body {"name":"q4-ledger"}
< 201 headers {"connection":"keep-alive","content-type":"application/json","keep-alive":"timeout=5","transfer-encoding":"chunked"}
< body {"id":"e2","name":"q4-ledger","status":"queued"}
list 200, create 201
secrets found in the dump: none
```

## Check it worked

Run the test file, which searches each dump for the six canaries.

```bash
node --test dump.test.mjs
```

```text output
1..10
# tests 10
# suites 0
# pass 10
# fail 0
# cancelled 0
# skipped 0
# todo 0
# duration_ms 1811.347825
```

Ten tests pass. One proves the switch prints nothing when `EXPORTS_DEBUG` is unset. Another
checks that the wire dump holds `share_token=[redacted]` while the server received the real token.
A third runs the Go demo both ways.

## When it goes wrong

A redactor that knows header names alone masks `Authorization` but misses four secrets, because
this API also sends them in a query string, a form body, a JSON response, and a signed URL. Add
the name rule for parameters and fields, and the value rule.

```bash
node pitfall.mjs
```

```text output
header names only: 4 leaked
  share token in the query
  client secret in a form body
  access token in a JSON response
  S3 signature in a signed URL
names and value patterns: 0 leaked
```

The S3 signature survives a redactor that splits query strings on `&`. Go's `encoding/json`
writes `&` inside a string as `\u0026`,[^3] as the Go dump shows, so the parameter after it
reads as part of the one before. `redact.mjs` treats `\u0026` as a separator, and a test feeds it
a body in that form.

The feature's entries lack the query string and the body you were looking for. That is the design
of the feature, which records the request as the pipeline described it. Add the `system.fetch`
wrapper for those, and expect `direct()` calls to appear only there.

## When not to do this

Do not leave the switch on in production. A redactor masks only the secrets it was written for,
so a field the next API version adds goes out in the clear.

Do not ship OpenAPI Generator's `Debug` or Python's debug level to a shared log. Both print
credentials as sent. If the client already comes from OpenAPI Generator, a redacting
`RoundTripper` in `HTTPClient` fixes the Go dump with no change of generator. If it comes from orval, the `mutator`
is already the single place every call passes through.

Do not adopt sdkgen to get a debug mode. Its feature masks what it records and records less than
this page needs, so the `system.fetch` wrapper is yours to write anyway. It earns its place when
you also want the same switch generated in every target language.

Do not reach for mitmproxy when the failure happens only in production, because no production
traffic passes through the proxy.

## Related how-tos

- [Reduce a failing SDK call to a minimal reproduction](/howto/minimal-reproduction-of-a-failing-sdk-call)

- [Choose the layer that instruments outbound API calls](/howto/choose-a-layer-to-instrument-outbound-calls)

- [Debug a query string the API rejects](/howto/debug-a-query-string-the-api-rejects)

- [Redact prompts and tool results in traces before export](/howto/redact-prompts-and-tool-results-in-traces)

- [Debug why a generated SDK sends the wrong content type](/howto/debug-wrong-content-type-from-generated-sdk)

## Last verified

Verified 2026-11-20 against Node 22.23.5, `@voxgig/create-sdkgen` 0.31.9, `@voxgig/sdkgen`
4.44.3, OpenAPI Generator 7.27.0 through `@openapitools/openapi-generator-cli` 2.42.2, orval
8.48.0, TypeScript 5.9.3, Go 1.24.7, and Python 3.13.18. Every output block is what the command
preceding it printed. The SDK, the Go client and the orval client were generated once, and their
output is committed. OpenAPI Generator's Python client was generated and read, not run. mitmproxy
was not run; its requirements come from its documentation.

[^1]: [RFC 6749](https://www.rfc-editor.org/rfc/rfc6749.html#section-2.3.1) allows a client to
send its secret in the request body, and calls that placement NOT RECOMMENDED, limited to clients
unable to use HTTP Basic. It also says the two parameters MUST NOT be included in the request URI.
Sent the recommended way, the secret travels in `Authorization`, where a header-name rule catches
it.

[^2]: The Python stand-in answers `HTTP/1.0` to a request sent as `HTTP/1.1`, because
`BaseHTTPRequestHandler` sets `protocol_version` to `HTTP/1.0` for backwards compatibility, as
the [`http.server` documentation](https://docs.python.org/3/library/http.server.html) puts it.
So the `send:` line of the dump says 1.1 and the `reply:` line says 1.0.

[^3]: The [`encoding/json` documentation](https://pkg.go.dev/encoding/json) gives the reason:
strings are escaped so that the JSON will be safe to embed inside HTML script tags, and
`SetEscapeHTML(false)` turns the escaping off where it interferes with readability. `Marshal`
always escapes, and an `Encoder` escapes until that call is made. The stand-in in this page's Go
demo writes no HTML and escapes all the same.