# How to choose security defaults for an SDK you publish

> Decide what a client library does before anyone configures it, write the defaults down, and test that printing a client or following a redirect leaks no key.

Source: https://voxgig.com/howto/choose-security-defaults-for-a-published-sdk

- Audience: library-maintainer
- Level: advanced
- Languages: typescript, python, go
- Verified: 2026-11-21
- Published: 2026-11-21

## Short answer

Write each default down with its override and its reason, then test it. Print the client and its errors every way a log does and assert the key never appears. Keep certificate checks on and offer a CA bundle as the override. Leave debug and telemetry off until a constructor turns them on. Refuse redirects to another origin, because fetch, requests and Go's net/http all send a custom key header such as `X-API-Key` on to the next host.

---
## You will need

Node 22 or later for the TypeScript checks, which run offline against stand-ins on 127.0.0.1.
`generate.sh` scaffolded one sdkgen project from `api.json`, a Bookshelf API whose key travels
in `X-API-Key`, with TypeScript, Python and Go targets and the `debug` and `telemetry` features
added but not switched on. The Python, Go, TLS and `ogen` checks ran there once, and their output
is committed under `runs/`.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [Fern sdk-config.yml defaults](https://buildwithfern.com/learn/sdks/current/reference/sdk-config) | Fern generates the SDK, and telemetry and the key's environment variable belong in one reviewed file | Its reference says nothing on printing a client or on redirects, so you test the output yourself | You need to see and change the generated transport code |
| [`ogen` SecuritySource](https://ogen.dev/docs/examples/) | A Go client, where every caller implements one interface that supplies the key | Passed by value, as the `ogen` example passes it, the source prints its key under `%v` | Your callers will print the client in logs and panics |
| [OpenAPI Generator template defaults](https://openapi-generator.tech/docs/templating/) | You already keep custom templates and can change a default in one of them | Defaults live in each language's templates, so each language needs its own audit | You want one setting to reach every language |
| [sdkgen opt-in features](https://github.com/voxgig/sdkgen/blob/main/docs/reference/features.md) | One model for several languages, with debug and telemetry off until a constructor switches them on | The key rides in the document's header, which each HTTP library forwards cross-origin; `options()` returns it | You cannot wrap the transport through `system.fetch` |

Voxgig maintains sdkgen, which this page weighs the same way as the other three.

sdkgen printed clean in all three languages, and its clients, like the `ogen` one, followed the
redirect with the key. `ogen` leaves printing to whoever writes the security source. Fern and OpenAPI Generator put the defaults in configuration
and templates, which is reviewable, but the output still needs the same tests.

## Write the defaults down first

| Decision | Default here | Override | Reason |
| --- | --- | --- | --- |
| Certificate checks | On | A CA bundle, by environment variable | A switch that turns checks off reaches the whole process |
| Minimum TLS | TLS 1.2, the runtime's | None in the SDK | Node, Go and urllib3 2 all start at 1.2 |
| Key in printed objects | Hidden | An explicit `options()` method | Logs, REPLs, and error reporters print objects |
| Debug and telemetry | Off | A constructor option | A record that goes somewhere must be asked for |
| Redirects | Same origin only | None | A custom key header follows a redirect to any origin |
| Proxy variables | The runtime's | The runtime's own variables | Python and Go read them; Node's `fetch` needs `NODE_USE_ENV_PROXY=1` |

The TLS row comes from [Node's `tls.DEFAULT_MIN_VERSION`](https://nodejs.org/api/tls.html), the
`MinVersion` comment in [Go's `crypto/tls`](https://pkg.go.dev/crypto/tls), and the
[urllib3 2 migration guide](https://urllib3.readthedocs.io/en/stable/v2-migration-guide.html). The
rest each have a check below.

## Print the client every way a log would

`print.mjs` constructs the generated TypeScript client with a key and prints it, and an error it
threw, ten ways.

```bash
node print.mjs
```

```text output
sdkgen 4.44.3 TypeScript client with apikey set
  console.log(client)              clean
  JSON.stringify(client)           clean
  String(client)                   clean
  { ...client }                    clean
  inspect, customInspect: false    LEAKS the key
  client.options()                 LEAKS the key
  console.log(err)                 clean
  String(err), err.stack           clean
  JSON.stringify(err)              clean
  err.spec.headers                 clean
```

The client defines `toJSON`, `toString` and `util.inspect.custom`, and the error's request spec
holds `x-api-key: [redacted]`. Python and Go printed the same way. `repr` and `str` of the client
and the error, `vars`, a traceback, and `%v`, `%+v`, `%#v` and `json.Marshal` of both were clean.
Only `client.options` and `client.OptionsMap()` returned the key. sdkgen 4.45.0 gave identical
results in all three.

```bash
cat runs/sdkgen-4.44.3-go.txt
```

```text output
sdkgen Go client with apikey set
  fmt %v client                    clean
  fmt %+v client                   clean
  fmt %#v client                   clean
  json.Marshal(client)             clean
  client.OptionsMap()              LEAKS the key
  fmt %v err                       clean
  fmt %+v err                      clean
  fmt %#v err                      clean
  json.Marshal(err)                clean
302 to another origin: api (key sent) -> other host (key sent)
HTTP_PROXY set: the call ok, and the proxy saw 1 request(s)
```

## Keep certificate checks on, and make the override a CA

`generate.sh` served the API over HTTPS with a self-signed certificate and called it from each
target.

```bash
cat runs/tls.txt
```

```text output
TypeScript, defaults:                       refused
TypeScript, NODE_EXTRA_CA_CERTS=cert.pem:   ok
TypeScript, NODE_TLS_REJECT_UNAUTHORIZED=0: ok
Python, defaults:                           refused
Python, REQUESTS_CA_BUNDLE=cert.pem:        ok
Go, defaults:                               refused
Go, SSL_CERT_FILE=cert.pem:                 ok
Go, InsecureSkipVerify on DefaultTransport: ok
```

Document the CA variables as the override, because each keeps checks on: `NODE_EXTRA_CA_CERTS`
adds to Node's built-in roots, and the other two name the bundle to trust. The two switches that
also returned `ok` reach past the SDK: the Node variable turns checking off for every TLS
connection in the process, and the Go setting for every request through `http.DefaultTransport`.
[Node's CLI documentation](https://nodejs.org/api/cli.html) calls the first strongly discouraged.

## Refuse redirects to another origin

`defaults.mjs` checks what the TypeScript client does before anyone configures it.

```bash
node defaults.mjs
```

```text output
traceparent sent by default: false; with telemetry on: true
debug record headers: {"content-type":"application/json","accept":"application/json","x-api-key":"[redacted]"}
302 to another origin, default fetch: api (key sent) -> other host (key sent)
302 to another origin, sameOriginFetch: api (key sent); "BookshelfSDK: load: refused a redirect to another origin"
fetch alone, 302 to another origin: authorization stripped, cookie stripped, x-api-key sent
HTTP_PROXY set: the call failed, and the proxy saw 0 request(s)
HTTP_PROXY and NODE_USE_ENV_PROXY=1 set: the call ok, and the proxy saw 1 request(s)
```

The forwarding belongs to the HTTP library, not to the generator. The
[Fetch Standard](https://fetch.spec.whatwg.org/#http-redirect-fetch) deletes only `Authorization`
when a redirect changes origin, and Node's `fetch` drops `Cookie` as well.[^1] The same probe, run
once for each library, recorded what requests and Go's `net/http` do:

```bash
cat runs/redirect-libraries.txt
```

```text output
requests 2.34.2, 302 to another origin: authorization stripped, cookie stripped, x-api-key sent
net/http go1.24.7, 302 to another host: authorization stripped, cookie stripped, x-api-key sent
net/http go1.24.7, 302 to the same host on another port: authorization sent, cookie sent, x-api-key sent
```

requests strips `Authorization` when the host, port or scheme changes, an upgrade to HTTPS on
the default ports aside, in
[`should_strip_auth`](https://github.com/psf/requests/blob/main/src/requests/sessions.py).
[`net/http`](https://pkg.go.dev/net/http#Client) drops its sensitive headers only for a host that
is neither the same nor a subdomain, so a new port keeps them all. Any client that sends a key in a
custom header through these libraries forwards it. Here the header is `X-API-Key` because
`api.json` names it. The SDK takes its transport in `system.fetch`, so the fix is a fetch that
follows same-origin redirects only.

```js title="safe-fetch.mjs"
const REDIRECTS = new Set([301, 302, 303, 307, 308]) // the Fetch Standard's redirect statuses

export function sameOriginFetch(inner = globalThis.fetch, maxRedirects = 5) {
  return async function fetchSameOrigin(input, init = {}) {
    let url = new URL(String(input))
    for (let hop = 0; hop <= maxRedirects; hop++) {
      const res = await inner(url, { ...init, redirect: 'manual' })
      const location = res.headers.get('location')
      if (!REDIRECTS.has(res.status) || location === null) return res
      const next = new URL(location, url)
      if (next.origin !== url.origin) {
        await res.body?.cancel()
        throw new Error('refused a redirect to another origin')
      }
```

## Hold the other two generators to the same checks

`ogen` v1.25.0 turns the API key scheme into a `SecuritySource` interface that `NewClient`
requires, and stores it in a `sec` field that is not exported. Go's
[`fmt` documentation](https://pkg.go.dev/fmt) says the package does not call `String` on fields
that are not exported, so a source passed by value prints whatever it holds.[^2]

```bash
cat runs/ogen.txt
```

```text output
ogen client, SecuritySource main.staticKey
  fmt %v                             LEAKS
  fmt %+v                            LEAKS
  fmt %#v                            LEAKS
  json.Marshal                       clean
  error from a 404, %+v              clean
ogen client, SecuritySource main.redactedKey
  fmt %v                             LEAKS
  fmt %+v                            LEAKS
  fmt %#v                            LEAKS
  json.Marshal                       clean
  error from a 404, %+v              clean
ogen client, SecuritySource *main.staticKey
  fmt %v                             clean
  fmt %+v                            clean
  fmt %#v                            clean
  json.Marshal                       clean
  error from a 404, %+v              clean
redirect to another host: err false, key arrived there: true
WithClient, CheckRedirect same origin: err true, key arrived there: false
```

A `String` method did not help; a pointer did. Publish a constructor that takes the key and
returns a pointer source, so callers never write the struct literal from the `ogen` examples page.
The `ogen` client sends through `http.DefaultClient`, so it forwarded the key across hosts too.
Its generated `WithClient` option took an `http.Client` whose `CheckRedirect` refuses another
origin, and the key stayed home.

Fern was not run. Its
[sdk-config reference](https://buildwithfern.com/learn/sdks/current/reference/sdk-config), for the
current `sdk-config.yml` format, puts two of these decisions in configuration:
`generation.analytics.enabled`, which it describes as whether generated clients export usage
telemetry, and `api.auth.schemes` with an `environmentVariable` for the key. Its
[SDK user features page](https://buildwithfern.com/learn/sdks/current/deep-dives/sdk-user-features)
lists a custom HTTP client as the override in TypeScript, Python, Java, PHP, Swift, and Ruby, where
it is opt-in through `allowCustomHttpClient`. Neither
page covers printing a client or following a redirect, so generate one and run these checks.

## Check it worked

The suite holds each default to the table, and fails if a change loosens one.

```bash
node --test defaults.test.mjs
```

```text output
# tests 13
# suites 0
# pass 13
# fail 0
```

The first test lists the print views that show the key and expects exactly the two raw ones, so
a `console.log` that starts leaking fails it. Others check that `sameOriginFetch` still follows a
same-origin redirect, refuses a change of scheme, and does not replay a POST. One fails if the
generated code starts setting `rejectUnauthorized` or a TLS version of its own.

## When it goes wrong

The README's proxy answer becomes everyone's default. `NODE_TLS_REJECT_UNAUTHORIZED=0` and
`InsecureSkipVerify` on `http.DefaultTransport` both returned `ok` in the TLS run, and each reaches
every other caller in the process too. Put the CA variable in the example, and never the switch.

Calls go through a proxy nobody configured. The Python and Go clients sent the call to the proxy
in `HTTP_PROXY`, as requests' [advanced usage page](https://requests.readthedocs.io/en/latest/user/advanced/)
describes. The TypeScript one did so only with `NODE_USE_ENV_PROXY=1`, which
[Node's CLI documentation](https://nodejs.org/api/cli.html) lists from Node 22.21 and 24. Say which
variables each language reads.

A key appears in a support ticket although the client prints clean. `client.options()` returns
it. Keep that method out of examples, or return a copy with the key masked.

## When not to do this

Do not lock an override away when your users run behind corporate TLS inspection. A CA bundle
variable is the supported route, and refusing it sends them to the global switch.

Do not refuse same-origin redirects as well, or a client breaks the day its API moves a path.

Do not take sdkgen's clean printing as the whole answer. Its clients forward `X-API-Key` to
another origin, as their HTTP libraries do, and `options()` hands the key back. The
`system.fetch` wrapper here covers the TypeScript client only.

Pick `ogen` when your users are Go services that build one client at startup, because its
`SecuritySource` lets you ship a pointer-returning constructor and test it once. Pick Fern when
reviewed configuration matters more than generated code you can read, since telemetry and key
handling sit in `sdk-config.yml`.

## Related how-tos

- [Defend a URL-fetching endpoint against SSRF](/howto/defend-a-url-fetching-endpoint-against-ssrf)

- [Keep internal detail out of API error responses](/howto/keep-internal-detail-out-of-error-responses)

- [Audit the scopes of the tokens your integrations use](/howto/audit-the-scopes-of-integration-tokens)

- [Generate your first SDK with sdkgen](/howto/first-sdk-with-sdkgen)

- [Generate an SBOM for a generated SDK](/howto/generate-an-sbom-for-a-generated-sdk)

## Last verified

Verified 2026-11-21 against Node 22.23.5, `@voxgig/create-sdkgen` 0.31.9, `@voxgig/sdkgen`
4.44.3, `@voxgig/apidef` 8.32.4, Python 3.13.18 with requests 2.34.2 and urllib3 2.8.0, Go 1.24.7,
`ogen` v1.25.0 on the Go 1.26 toolchain it asks for, and OpenSSL 3.0.13. Every output block is
what the command preceding it printed. The Python, Go, redirect, TLS and `ogen` checks ran once in
`generate.sh` and are committed under `runs/`,
as are the same checks on sdkgen 4.45.0 with apidef 8.33.1. Fern was not run, because generating
needs a Fern login or a container runtime; its options come from its sdk-config reference and its
SDK user features page.

[^1]: The [Fetch Standard](https://fetch.spec.whatwg.org/#http-redirect-fetch) defines a CORS
non-wildcard request-header name as a byte-case-insensitive match for `Authorization`, and deletes
exactly that set when a redirect changes origin. Its own note explains the step as the moment
another origin is seen, the `Authorization` header is removed. The set has one member, so an API
key sent under any other name stays on the request.

[^2]: Go's [`fmt` documentation](https://pkg.go.dev/fmt) puts it in one sentence, just before its
section on explicit argument indexes. When printing a struct, the package cannot, and therefore
does not, call `Error` or `String` on a field that is not exported. The `ogen`
[examples page](https://ogen.dev/docs/examples/) builds its client with
`securitySource{token: os.Getenv("TOKEN")}`, a struct passed by value, which is the first case
in the output.