How-to › Release and secure packages

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.

Audience
Library maintainer
Level
advanced
Topic
Harden clients and servers
Languages
TypeScript, Python and Go
Verified

A user pastes console.log(client) into a support thread, and your client prints the live key. Another copies NODE_TLS_REJECT_UNAUTHORIZED=0 from a proxy answer, and every HTTPS call in that process stops checking certificates. Your API answers one request with a 302 to a CDN, and the X-API-Key header follows it there.

What you get

You will end up with tests that fail when a change loosens a default, and a table that gives each default your SDK ships its override and its reason. This is for you if you publish a client other people configure.

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

ApproachWhen it fitsWhat it costs youWhen to pick something else
Fern sdk-config.yml defaultsFern generates the SDK, and telemetry and the key’s environment variable belong in one reviewed fileIts reference says nothing on printing a client or on redirects, so you test the output yourselfYou need to see and change the generated transport code
ogen SecuritySourceA Go client, where every caller implements one interface that supplies the keyPassed by value, as the ogen example passes it, the source prints its key under %vYour callers will print the client in logs and panics
OpenAPI Generator template defaultsYou already keep custom templates and can change a default in one of themDefaults live in each language’s templates, so each language needs its own auditYou want one setting to reach every language
sdkgen opt-in featuresOne model for several languages, with debug and telemetry off until a constructor switches them onThe key rides in the document’s header, which each HTTP library forwards cross-origin; options() returns itYou 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

DecisionDefault hereOverrideReason
Certificate checksOnA CA bundle, by environment variableA switch that turns checks off reaches the whole process
Minimum TLSTLS 1.2, the runtime’sNone in the SDKNode, Go and urllib3 2 all start at 1.2
Key in printed objectsHiddenAn explicit options() methodLogs, REPLs, and error reporters print objects
Debug and telemetryOffA constructor optionA record that goes somewhere must be asked for
RedirectsSame origin onlyNoneA custom key header follows a redirect to any origin
Proxy variablesThe runtime’sThe runtime’s own variablesPython and Go read them; Node’s fetch needs NODE_USE_ENV_PROXY=1

The TLS row comes from Node’s tls.DEFAULT_MIN_VERSION, the MinVersion comment in Go’s crypto/tls, and the urllib3 2 migration guide. The rest each have a check below.

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

node print.mjs
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.

cat runs/sdkgen-4.44.3-go.txt
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.

cat runs/tls.txt
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 calls the first strongly discouraged.

Refuse redirects to another origin

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

node defaults.mjs
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 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:

cat runs/redirect-libraries.txt
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. net/http 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.

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 says the package does not call String on fields that are not exported, so a source passed by value prints whatever it holds.2

cat runs/ogen.txt
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, 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 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.

node --test defaults.test.mjs
# 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 describes. The TypeScript one did so only with NODE_USE_ENV_PROXY=1, which Node’s CLI documentation 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.

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.

Footnotes

  1. The Fetch Standard 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. ↩︎ Back to text

  2. Go’s fmt documentation 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 builds its client with securitySource{token: os.Getenv("TOKEN")}, a struct passed by value, which is the first case in the output. ↩︎ Back to text

Read this page as markdown · All how-to guides

Generate the client instead of writing it#

Retries, timeouts, pagination and auth are the same problems in every client. Voxgig generates them from your OpenAPI description, in 23 languages, from one model.

Listen to Fireside, the Voxgig podcast

Since 2018, Richard Rodger has talked with developer advocates, event organizers, and the people who build developer-facing companies about the specifics of the work.