Secrets, cryptography and supply chain · 6 MIN READ

Keep secrets out of logs and errors with a type that refuses to print itself

Wrap credentials in a Secret type that redacts itself in fmt, slog and JSON, redact credentials in URLs, and load secrets with errors that name the source but never the value.

Most leaked credentials are not stolen from a vault; they are printed. A startup line that logs the configuration with %+v, an error that wraps a connection string, a debug endpoint that dumps settings: each copies the secret into log storage that more people can read, for longer, than the secret store itself. Make printing safe by default and make revealing the value an explicit, searchable call.

security · A MAP OF THE IDEA

  1. Load once at startup
  2. Wrap in a Secret type
  3. Reveal at point of use
  4. Canary-test every sink

Useful when

  • Careless log lines and %+v dumps print a placeholder instead of the value.
  • Every intentional use is a searchable Reveal call.

Watch out

  • Unexported fields bypass fmt methods, and encoding/json skips them silently.
  • Redacted hides only the userinfo password, not tokens in the query string.

Implementation & operation cost: A small wrapper type, a Reveal call at each use site and one canary test per output channel. It does not protect memory, core dumps or values already copied into plain strings.

01

Follow a password from config to log line

Trace a database password through a typical service. It is read from the environment into a Config struct; the struct is logged at startup so operators can see what was loaded; the password is placed in a connection URL; and when the database is down, the URL appears in a wrapped error that is logged on every retry. None of these steps looks like a leak in review. The log pipeline then ships each line to an aggregator, to backups and perhaps to a vendor, where access rules and retention are looser than in your secret store. Once the value is there, the only safe response is rotation. Prevention works best at the type level: if the value cannot print itself, the careless log line stays harmless.

02

A Secret type that redacts every formatting path

Secret keeps its value in an unexported field and implements four interfaces, because different encoders take different paths. fmt.Formatter covers every fmt verb, including %x and %q, and takes precedence over String and GoString. slog.LogValuer is resolved by slog handlers when a Secret is an attribute value. json.Marshaler covers JSON log handlers and API responses that embed the struct. String remains for code that asks for a fmt.Stringer directly. The program pushes a fake canary value through each path and checks whether it survived.

go
package main

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"log/slog"
	"net/url"
	"strings"
)

const redacted = "[REDACTED]"

// Secret holds a credential. Every formatting path prints a placeholder;
// only Reveal returns the value, so each real use is visible in review.
type Secret struct{ value string }

func NewSecret(v string) Secret { return Secret{value: v} }

func (s Secret) Reveal() string { return s.value }

func (Secret) String() string                { return redacted }
func (Secret) Format(f fmt.State, verb rune) { io.WriteString(f, redacted) }
func (Secret) LogValue() slog.Value          { return slog.StringValue(redacted) }
func (Secret) MarshalJSON() ([]byte, error)  { return json.Marshal(redacted) }

type Config struct {
	Addr       string
	DBPassword Secret
}

func main() {
	const canary = "canary-7f3a" // a fake value we can search for

	type plain struct{ Addr, DBPassword string }
	fmt.Println("plain field leaks:", strings.Contains(fmt.Sprintf("%+v", plain{":8080", canary}), canary))

	cfg := Config{Addr: ":8080", DBPassword: NewSecret(canary)}
	fmt.Printf("%+v\n", cfg)
	fmt.Printf("%#v %x %q\n", cfg.DBPassword, cfg.DBPassword, cfg.DBPassword)

	type hidden struct{ token Secret }
	fmt.Println("unexported field leaks:", strings.Contains(fmt.Sprintf("%+v", hidden{NewSecret(canary)}), canary))

	var buf bytes.Buffer
	opts := &slog.HandlerOptions{ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
		if a.Key == slog.TimeKey && len(groups) == 0 {
			return slog.Attr{} // drop the timestamp so the output is stable
		}
		return a
	}}
	for _, h := range []slog.Handler{slog.NewJSONHandler(&buf, opts), slog.NewTextHandler(&buf, opts)} {
		slog.New(h).Info("config loaded", "db_password", cfg.DBPassword, "config", cfg)
	}
	fmt.Print(buf.String())

	dsn, err := url.Parse("postgres://orders:" + canary + "@db.internal.example:5432/orders")
	if err != nil {
		panic(err)
	}
	fmt.Println("url String leaks:", strings.Contains(dsn.String(), canary))
	fmt.Println(fmt.Errorf("connect %s: %w", dsn.Redacted(), errors.New("connection refused")))
	fmt.Println("leak found in any output:", strings.Contains(buf.String(), canary))
}
Read the code

A plain string field prints verbatim under %+v. Config.DBPassword is an exported field, so fmt calls Secret.Format on it and every verb prints [REDACTED]. The hidden struct shows the trap: fmt cannot invoke methods on unexported fields, so it falls back to reflection and prints {token:{value:canary-7f3a}}. The JSON handler resolves db_password through LogValue and encodes the nested config with json.Marshal, which calls MarshalJSON; the text handler formats the nested struct with %+v, which reaches Format. url.URL.String includes the password, while Redacted replaces it with xxxxx before the URL enters an error string. The final line confirms the canary never reached the log buffer.

03

Know which path each encoder takes

The type protects only the paths it implements, so learn the rules that bypass it. fmt and encoding/json both ignore methods on unexported struct fields: fmt prints the raw contents and json silently skips the field. slog resolves LogValuer on attribute values and inside groups, not inside struct fields, so a nested Secret relies on MarshalJSON in a JSON handler and on Format in a text handler. Calling Reveal hands out a plain string that no longer protects itself, so do it at the last moment, inside the call that needs it, such as building a driver configuration. Reflection-based dumpers and some third-party loggers walk struct fields directly; check how each one you use prints a value. If configuration is decoded from a file, give Secret an UnmarshalText method so it never exists as a plain string field. Keep the method name distinctive, so a search for Reveal lists every intentional use.

04

Redact URLs and fail loudly without the value

Connection strings carry credentials in the userinfo part, and url.URL.String prints them. Redacted replaces only the password; it does not touch tokens in the query string, so keep API keys in headers, because proxies and access logs record URLs. The net/http client already replaces the password with *** in the *url.Error it returns, but errors you build with fmt.Errorf get no such help. When loading, accept either NAME or NAME_FILE, the convention for secrets that container platforms mount as files; reject both being set, trim the trailing newline that editors add, and refuse empty values. Every error names the variable or the file, never the content.

go
package main

import (
	"fmt"
	"io"
	"os"
	"path/filepath"
	"strings"
)

type Secret struct{ value string }

func (s Secret) Reveal() string              { return s.value }
func (Secret) Format(f fmt.State, verb rune) { io.WriteString(f, "[REDACTED]") }

// loadSecret reads NAME_FILE (a mounted secret file) or NAME, never both.
// Errors name the variable or the path, never the value.
func loadSecret(name string) (Secret, error) {
	path, fromFile := os.LookupEnv(name + "_FILE")
	value, fromEnv := os.LookupEnv(name)
	switch {
	case fromFile && fromEnv:
		return Secret{}, fmt.Errorf("%s: set %s or %s_FILE, not both", name, name, name)
	case fromFile:
		b, err := os.ReadFile(path)
		if err != nil {
			return Secret{}, fmt.Errorf("%s_FILE: %w", name, err)
		}
		value = strings.TrimRight(string(b), "\r\n")
	case !fromEnv:
		return Secret{}, fmt.Errorf("%s: not set; provide %s or %s_FILE", name, name, name)
	}
	if value == "" {
		return Secret{}, fmt.Errorf("%s: empty value", name)
	}
	return Secret{value: value}, nil
}

func main() {
	dir, err := os.MkdirTemp("", "secret-load")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(dir)
	path := filepath.Join(dir, "db_password")
	if err := os.WriteFile(path, []byte("canary-7f3a\n"), 0o600); err != nil {
		panic(err)
	}

	os.Unsetenv("ORDERS_DB_PASSWORD")
	os.Setenv("ORDERS_DB_PASSWORD_FILE", path)
	db, err := loadSecret("ORDERS_DB_PASSWORD")
	fmt.Println(db, err, db.Reveal() == "canary-7f3a")

	os.Setenv("ORDERS_DB_PASSWORD", "also-set")
	_, err = loadSecret("ORDERS_DB_PASSWORD")
	fmt.Println(err)

	os.Unsetenv("ORDERS_API_TOKEN")
	os.Unsetenv("ORDERS_API_TOKEN_FILE")
	_, err = loadSecret("ORDERS_API_TOKEN")
	fmt.Println(err)

	os.Setenv("ORDERS_API_TOKEN", "")
	_, err = loadSecret("ORDERS_API_TOKEN")
	fmt.Println(err)
}
Read the code

This second program compiles as shown; run it in your own environment. It writes a test secret under os.TempDir with mode 0600 and points ORDERS_DB_PASSWORD_FILE at it. The first line prints [REDACTED] <nil> true: the loaded Secret hides itself while Reveal still returns the canary. Setting both forms is ambiguous and fails; a missing variable fails with a message that tells the operator exactly what to provide; an empty value is treated as an error rather than silently connecting without a password. Call loadSecret during startup so a bad deployment fails before it accepts traffic.

05

Choose where secrets live

Environment variables are convenient but broad: every child process inherits them, Linux exposes them through /proc to the same user and to root, crash reporters often capture them, and os.Unsetenv after reading does not erase copies a supervisor already holds. Mounted files can carry tight permissions, can be rotated by replacing the file, and keep the value out of the environment. A secret manager adds audit trails, short-lived credentials and automatic rotation, at the cost of a network dependency during startup. Whatever the source, load secrets once at startup into Secret values, re-read files on a signal or timer if rotation must not need a restart, and never log a prefix of the value: a few characters of a short password narrow guessing considerably. To correlate rotations, log a key ID or version number, which is not secret.

06

Prove it with a canary test

Add one test per output channel: build the real Config from a canary value, run the code that logs it at startup, render the error your connection code produces, encode the debug endpoint's JSON, and fail if the canary appears anywhere. The test is cheap and catches the regression that matters most, a new credential field added as a plain string. Keep a log-pipeline scrubber for known token formats as a second line of defense, but treat it as a backstop: by the time it runs, the secret has already left the process.

go
func TestStartupLogDoesNotLeak(t *testing.T) {
	const canary = "canary-7f3a"
	var buf bytes.Buffer
	logger := slog.New(slog.NewJSONHandler(&buf, nil))
	cfg := Config{Addr: ":8080", DBPassword: NewSecret(canary)}

	logStartup(logger, cfg) // the function production calls at boot

	if strings.Contains(buf.String(), canary) {
		t.Fatalf("secret leaked into the startup log: %s", buf.String())
	}
}
Read the code

This _test.go fragment belongs in your service's package and runs with go test in your own environment; it also needs the bytes, log/slog, strings and testing imports. logStartup stands for whatever function production calls at boot. Testing that function rather than a copy of it is what makes the test meaningful. Printing the buffer on failure is safe here because the canary is not a real credential.

TAKE THIS WITH YOU

Wrap credentials in a type whose every formatting path prints a placeholder, keep secret fields exported or explicitly encoded, redact URLs before they reach errors, and fail at startup with messages that name the source, never the value.

Check your understanding

A Secret type implements Format and String, but another struct holds it in an unexported field. What does %+v print for that struct?

Go to the source

Progress stays in this browser. No account needed.