Master data flows in Go: io.Reader/Writer compositors with Tee, Pipe, and MultiWriter, backpressure management in channel pipelines without goroutine leaks, Kafka integration with franz-go and sarama including batching and rebalancing, efficient batch inserts with pgx COPY and transaction chunking, plus a complete streaming embedding pipeline from files to chunks to vectors.
It is a Tuesday when "Kant & Curves" receives the external pentester's report. Finding 3: the loyalty-card customer data sits on disk unencrypted. Finding 4: staff-account password hashing still relies on a single SHA-256 pass. Operations wants two things from you: encrypt sensitive fields at rest, and hash passwords properly. The good news for Go developers: most of what that takes ships in the standard library — crypto/aes, crypto/cipher, crypto/rand — plus exactly one package from the x-series: golang.org/x/crypto/argon2.
Before any code gets written, the most important fork in the road: encryption and hashing are two different tools answering two different questions. Encryption (AES-GCM) is reversible — later, the plaintext must come back out, for example to display an address. Hashing (Argon2id) is deliberately irreversible — for a password you only ever verify, never retrieve. Anyone who "encrypts" passwords instead of hashing them has not understood the question; anyone who hashes customer data the shop will need later has destroyed the data.
AES-GCM encrypts and seals at the same time
AES by itself is only a block cipher. GCM mode (Galois/Counter Mode) turns it into authenticated encryption: the ciphertext carries an authentication tag that is checked on open. Tampered or swapped ciphertexts fail during decryption instead of yielding garbage. That is why cipher.NewGCM is the standard route for symmetric encryption in Go — CBC without a MAC is attackable (padding oracles) and has no place in new code.
First, field encryption for the loyalty-card data. The key here comes from a 32-byte source (hex), the nonce is drawn fresh from crypto/rand, and it is prepended to the ciphertext — one column is all the database needs:
// internal/crypto/aesgcm.go — AES-256-GCM: encrypt with a fresh nonce
package crypto
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"errors"
"io"
)
func Encrypt(key, plaintext []byte) ([]byte, error) {
block, err := aes.NewCipher(key) // key must be 16, 24, or 32 bytes
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonce := make([]byte, gcm.NonceSize()) // 12 bytes in standard GCM
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
// Seal appends the tag; we prepend the nonce by passing it as dst
return gcm.Seal(nonce, nonce, plaintext, nil), nil
}
func Decrypt(key, sealed []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
if len(sealed) < gcm.NonceSize() {
return nil, errors.New("ciphertext too short")
}
nonce, ciphertext := sealed[:gcm.NonceSize()], sealed[gcm.NonceSize():]
return gcm.Open(nil, nonce, ciphertext, nil) // tag check included
}
// Terminal: go test ./internal/crypto/ -run TestRoundTrip -v
// → === RUN TestRoundTrip
// → --- PASS: TestRoundTrip (0.00s) — 24 bytes plaintext, plus 12 nonce + 16 tag on top
Second, password hashing for the staff accounts. Argon2id — from golang.org/x/crypto/argon2 — is the current OWASP-recommended standard because it derives keys that are expensive in both dimensions at once: CPU time and memory. That stalls the GPU and ASIC farms that burn through SHA-256 in microseconds. And because the parameters must travel with the hash (better hardware → harder parameters), you store them right in the PHC string format:
// internal/crypto/password.go — Argon2id hash with parameters in PHC format
package crypto
import (
"crypto/rand"
"crypto/subtle"
"fmt"
"golang.org/x/crypto/argon2"
)
const (
argonTime = 1 // passes
argonMemory = 64 * 1024 // 64 MiB per hash — OWASP ballpark
argonThreads = 4
)
func HashPassword(password string) (string, error) {
salt := make([]byte, 16)
if _, err := rand.Read(salt); err != nil {
return "", err
}
key := argon2.IDKey([]byte(password), salt,
argonTime, argonMemory, argonThreads, 32)
// Store parameters WITH the hash — otherwise you can never verify again
return fmt.Sprintf("$argon2id$v=19$m=%d,t=%d,p=%d$%x$%x",
argonMemory, argonTime, argonThreads, salt, key), nil
}
func VerifyPassword(password, phc string) bool {
var m uint32
var t uint32
var p uint8
var salt, key []byte
if _, err := fmt.Sscanf(phc, "$argon2id$v=19$m=%d,t=%d,p=%d$%x$%x",
&m, &t, &p, &salt, &key); err != nil {
return false
}
got := argon2.IDKey([]byte(password), salt, t, m, p, uint32(len(key)))
return subtle.ConstantTimeCompare(got, key) == 1 // constant-time comparison
}
// Terminal: go test ./internal/crypto/ -run TestPassword -v
// → Hash: $argon2id$v=19$m=65536,t=1,p=4$9f12…$a3b7…
// → Verify: correct password → true, typo → false (in constant time)
For completeness, the third ingredient that briefings love to skip: SecureRandom. Keys, nonces, and salts need randomness an attacker cannot predict. That is what crypto/rand is for — math/rand is not, even though it has been auto-seeded since Go 1.20: it is built for simulations and tests, not against adversaries. Rule of thumb: anything that must stay secret or must be unique comes from crypto/rand; everything else may come from math/rand (or math/rand/v2 since Go 1.22).
What actually needs encrypting — and where exactly the boundary between the trusted core and the wide world runs — is not a Go question but an architecture question; the trust boundaries and zone layering are covered in Module 9 of the architecture course. The Go takeaway from it is plain: the key never lives next to the data it protects — otherwise you are locking the safe and taping the key to its door.
⚠ Common mistake: Hard-wiring the nonce or deriving it from a deterministic counter, "so the tests stay reproducible." GCM breaks twice when a nonce repeats under the same key: two ciphertexts sharing a nonce form a two-time pad from which plaintext can be reconstructed — and worse, the authentication function leaks its key part, letting attackers forge valid ciphertexts afterwards. Nonces are single-use: fresh from
crypto/rand, 12 bytes, new for every encryption. For reproducible tests, inject the randomness (a small interface instead of callingrand.Readerdirectly) — never make production deterministic.
Check: A colleague encrypts two messages with AES-GCM using the same key and the same nonce. What happens?
Answer: The key-plus-nonce pair acts like a reused one-time pad: plaintexts become reconstructible and the tag key leaks — forgery becomes possible
The common misconception is that the authentication tag saves the day. Under GCM nonce reuse with the same key you get the one-time-pad problem all over again: XORing the two ciphertexts strips the encryption. On top of that, the GHASH key component becomes attackable, which enables forgery. The library cannot catch this — it has no idea which other nonces you used elsewhere. Per-key nonce uniqueness is part of GCM's contract.
Takeaways:
crypto/aes + crypto/cipher) for data that must come back; Argon2id (golang.org/x/crypto/argon2) for passwords that only get checked.crypto/rand; prepend it to the ciphertext.crypto/subtle.ConstantTimeCompare.crypto/rand, never math/rand — not even since the Go 1.20 auto-seeding.The middleware from lesson 57 validates bearer tokens against the database — one query per request. As traffic grows, the team wants that lookup gone and moves to JWTs: login issues a signed token, and every subsequent middleware only verifies the signature. Stateless, fast, horizontally scalable. But only if three things line up: the library, the verification, and the lifetime.
The library first, because a piece of Go history confuses people here: the ancient github.com/dgrijalva/jwt-go has been unmaintained for years and carries CVE-2020-26160, a flaw in audience validation. The community forked the project; the maintained path today is github.com/golang-jwt/jwt/v5 — a major-versioned module, actively maintained, with API breaks from the original fork cleanly bundled into v5. New code imports v5 and nothing else.
A JWT is a signed envelope, not a locked safe
A JWS token has three base64 parts: header, payload, signature. Signed means: tamper-evident against third parties. It does NOT mean secret — anyone who gets hold of the token can read the payload (just base64-decode it). Passwords, secrets, or internals therefore never belong in claims. If you need confidentiality, you need encryption (JWE) — a different tool.
First, issuing. Claims live in a dedicated struct embedding jwt.RegisteredClaims — the standard fields iss, sub, exp, iat become type-safe instead of loose strings:
// internal/auth/issue.go — issue an access token, valid for 15 minutes
package auth
import (
"time"
"github.com/golang-jwt/jwt/v5"
)
type StaffClaims struct {
Role string `json:"role"` // "warehouse" or "admin" — authorization follows lesson 57 style
jwt.RegisteredClaims
}
func IssueAccessToken(secret []byte, user, role string) (string, error) {
now := time.Now()
claims := StaffClaims{
Role: role,
RegisteredClaims: jwt.RegisteredClaims{
Issuer: "bookstore",
Subject: user,
IssuedAt: jwt.NewNumericDate(now),
ExpiresAt: jwt.NewNumericDate(now.Add(15 * time.Minute)), // deliberately short
},
}
return jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(secret)
}
// Terminal: issue a token for Lena and inspect it
// → eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYWRtaW4iLCJpc3MiOiJib29rc3RvcmUiLCJzdWIiOiJsZW5hIn0.kQ9…
// → (base64 of the middle part: role=admin, iss=bookstore, sub=lena, exp=… — readable by anyone!)
Then verification — where the actual pitfalls live. ParseWithClaims with a keyfunc, the algorithm pinned to HS256, expiry enforced:
// internal/auth/verify.go — verify a token: alg pinned, exp required
package auth
import (
"errors"
"github.com/golang-jwt/jwt/v5"
)
func VerifyAccessToken(secret []byte, raw string) (StaffClaims, error) {
claims := &StaffClaims{}
_, err := jwt.ParseWithClaims(raw, claims,
func(t *jwt.Token) (interface{}, error) { return secret, nil },
jwt.WithValidMethods([]string{"HS256"}), // do NOT trust the alg from the header
jwt.WithExpirationRequired(), // v5 option: missing exp = error
)
if err != nil {
switch {
case errors.Is(err, jwt.ErrTokenExpired):
return StaffClaims{}, errors.New("token expired — run refresh")
default:
return StaffClaims{}, errors.New("token invalid")
}
}
return *claims, nil
}
// Middleware hookup (Gin, succeeding lesson 57):
// claims, err := auth.VerifyAccessToken(secret, bearer)
// → valid token: claims = {Role: admin, Subject: lena} → request proceeds
// → expired: 401 {"error":"token expired — run refresh"}
// → foreign signature: 401 {"error":"token invalid"}
v5 validates exp and nbf automatically whenever the fields are present — WithExpirationRequired sharpens that: if exp is missing entirely, the token is rejected instead of silently accepted. A small, expensive option.
Third, rotation — stateless does not mean valid forever. The proven pattern combines two token kinds: an access token with a lifetime of minutes (above: 15) and a refresh token with days, stored server-side in the database where it can be revoked. When the access token expires, the client trades the refresh token for a new pair — and the server rotates the refresh token itself on every use, so a stolen refresh only lives until the next refresh. When the signing key itself rotates, the kid header helps: the server publishes its keys as a JWKS (JSON Web Key Set) at a well-known URL, tokens name their key id in the header, and old keys stay valid for a grace period. With HS256 (symmetric), every verifying instance must know the secret — once the verifier is a different service, switch to RS256/EdDSA, where only the issuer holds the private key.
⚠ Common mistake: Writing the keyfunc so it blindly returns whatever fits the header's algorithm — and omitting
jwt.WithValidMethods. The classic: the server signs with RS256, verification fetches the public key; an attacker forges the header toalg: HS256and signs the token with HMAC using that very public key (which is allowed to be public knowledge). Verification hands it back as the HMAC secret and accepts the forged token. That is the historical alg-confusion hole in several frameworks. Always pin the allowed methods explicitly — then the library blocks the header trick for you.
Check: Why does jwt.WithValidMethods belong in every ParseWithClaims call?
Answer: It stops an attacker from claiming a different algorithm in the header and tricking the keyfunc into using the key the wrong way
The keyfunc initially does not know what the returned key is FOR — that is stated in the (attacker-controlled) header. Without pinning methods, an RS256 verifier can be tricked into treating a public key as an HMAC secret — the alg-confusion attack. WithValidMethods rejects any token whose header algorithm is not on the list, closing exactly that hole.
Takeaways:
github.com/golang-jwt/jwt/v5; the old github.com/dgrijalva/jwt-go is unmaintained (CVE-2020-26160) and belongs in no new code.jwt.RegisteredClaims — iss, sub, exp, iat type-safe instead of a loose string map.jwt.WithValidMethods) and require expiry (jwt.WithExpirationRequired).kid header and a JWKS endpoint do the work."Kant & Curves" is planning the customer platform, and product leadership asks the sensible question: why should we store customer passwords at all? The booksellers' cooperative already runs a central identity provider (IdP) — "Buchhaus ID". Customers log in there, and the shop receives delegated permission to recognize them. That is exactly the territory of OAuth2 (delegating access) and OpenID Connect (OIDC, authenticating the user), and in Go the standard cast is golang.org/x/oauth2 for the flows plus github.com/coreos/go-oidc/v3/oidc for ID-token verification.
The flow landscape in three sentences: Authorization Code with PKCE is the standard flow for web apps and SPAs — the browser fetches a code from the IdP, the backend exchanges it for tokens. Client Credentials is the service-to-service flow with no user involved — the billing service fetches its own token. The Implicit flow is dead (OAuth 2.1 buries it for good), and the Password Grant is on its way out too: both historically pushed tokens through the browser or passwords through the app.
OAuth2 delegates, OIDC authenticates — do not confuse the tokens
The access token is a key to an API: it says nothing reliable about WHO is acting. The identity sits in the ID token — a JWT the IdP issues and which must be verified against its public keys (JWKS). Anyone who just base64-decodes the access token and reads its claims as identity has read a token any app could have obtained for any user.
The first block starts the authorization-code flow including the two mandatory extras: state (CSRF protection) and PKCE (Proof Key for Code Exchange — since 2023 available directly in golang.org/x/oauth2 via oauth2.GenerateVerifier and oauth2.S256ChallengeOption):
// internal/idp/login.go — redirect to the IdP: state + PKCE
package idp
import (
"crypto/rand"
"encoding/hex"
"net/http"
"golang.org/x/oauth2"
)
func Login(cfg oauth2.Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// state: one-time value stored in the session — checked in the callback
state := make([]byte, 16)
rand.Read(state)
stateHex := hex.EncodeToString(state)
verifier := oauth2.GenerateVerifier() // 43+ chars, stays server-side
url := cfg.AuthCodeURL(stateHex,
oauth2.S256ChallengeOption(verifier)) // challenge in the query, verifier stays secret
http.Redirect(w, r, url, http.StatusFound)
}
}
// Terminal: curl -s -i localhost:8080/login | grep Location
// → Location: https://idp.buchhaus.example/authorize?client_id=bookstore-shop
// → &redirect_uri=…&response_type=code&scope=openid+email&state=8f3a9c…
// → &code_challenge=YkQz…&code_challenge_method=S256
The callback checks the state, exchanges code plus PKCE verifier for tokens, and verifies the ID token with go-oidc:
// internal/idp/callback.go — exchange the code, verify the ID token
package idp
import (
"net/http"
"github.com/coreos/go-oidc/v3/oidc"
"golang.org/x/oauth2"
)
func Callback(cfg oauth2.Config, provider *oidc.Provider, sessions SessionStore) http.HandlerFunc {
verifier := provider.Verifier(&oidc.Config{ClientID: cfg.ClientID})
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
// 1. Check state against the session — do NOT skip this
if !sessions.CheckState(r, r.URL.Query().Get("state")) {
http.Error(w, "state mismatch", http.StatusBadRequest)
return
}
// 2. Exchange code + PKCE verifier for tokens (scope openid was required)
tok, err := cfg.Exchange(ctx, r.URL.Query().Get("code"),
oauth2.VerifierOption(sessions.PopVerifier(r)))
if err != nil {
http.Error(w, "code exchange failed", http.StatusBadGateway)
return
}
// 3. Verify the ID token: signature against the IdP's JWKS, iss, aud, exp
rawIDToken, _ := tok.Extra("id_token").(string)
idToken, err := verifier.Verify(ctx, rawIDToken)
if err != nil {
http.Error(w, "invalid ID token", http.StatusUnauthorized)
return
}
var user struct {
Email string `json:"email"`
}
idToken.Claims(&user) // now, and only now: identity
sessions.Login(w, r, user.Email)
}
}
// Terminal: browser follows the redirect, user signs in, IdP redirects back
// → GET /callback?code=abc123&state=8f3a9c… → 303 See Other, cookie set
// → user recognized as: ada@buchhaus.example
For service-to-service use cases there is the client-credentials flow — and here golang.org/x/oauth2 shows its most convenient side: the TokenSource renews expiring tokens automatically, invisibly to the caller:
// internal/billing/client.go — client credentials: token fetching becomes invisible
package billing
import (
"context"
"net/http"
"golang.org/x/oauth2"
"golang.org/x/oauth2/clientcredentials"
)
func NewClient(ctx context.Context, cfg clientcredentials.Config) *http.Client {
// TokenSource fetches, caches, and renews tokens — including retry on 401
return oauth2.NewClient(ctx, cfg.TokenSource(ctx))
}
// Terminal: billing service calls the invoicing API
// → GET /v1/invoices → 200 (token fetching + refresh ran automatically)
// → Debug log: oauth2: token expired, refreshing (happens exactly once, silently)
Where AuthN ends and AuthZ begins, how layers of authentication and authorization stack, and what still needs checking inside a trust boundary — that is architecture territory, covered in Module 9 of the architecture course. The Go side here delivers the building blocks: a verified ID token for AuthN, claims in the access token for AuthZ.
⚠ Common mistake: Implementing the callback without a state check, because "the IdP is the only one redirecting here anyway." Login CSRF still works: the attacker signs in at the IdP themselves, intercepts the callback code, and lures the victim onto the complete callback URL — the victim ends up in a session that belongs to the attacker (a session-fixation variant). The state check is two lines: generate the value before the redirect and store it in the session, then compare against the query parameter in the callback. In the code above it is step 1 — deliberately ahead of the token exchange.
Check: The platform should display the customer's name after login. Which token delivers the reliable identity — and how?
Answer: The ID token: verify it against the issuer's JWKS (signature, iss, aud, exp) and only then read the claims
Base64-decoding the access token is the classic shortcut: it is meant for APIs and says nothing reliable about the user — depending on the grant, any app could have obtained it for anyone. The identity sits in the ID token, a JWT from the issuer that MUST be verified against its public keys (the verifier from go-oidc does that). And yes, claims like the name live in the ID token itself — no UserInfo roundtrip needed.
Takeaways:
golang.org/x/oauth2 ships GenerateVerifier, S256ChallengeOption, and VerifierOption since 2023.state before the redirect and check it in the callback — otherwise login is CSRF-able.github.com/coreos/go-oidc/v3/oidc against the issuer's JWKS; the access token delegates access, not identity.clientcredentials.Config; the TokenSource from golang.org/x/oauth2 renews tokens automatically.Finding 1 of the pentest report is the most embarrassing one: an early version of the accounting service committed a .env with the PostgreSQL password to the repo — two years ago, deleted after three weeks, but immortal in Git history. Finding 2 right behind it: the same password sits in a deployment environment variable and shows up verbatim in docker inspect. Operations' verdict: rotate every secret, and get a system that takes rotation, auditing, and distribution seriously.
First, an honest assessment of environment variables, because the twelve-factor app preaches them: for CONFIGURATION (ports, log levels, feature flags) env is exactly right — not secret, not critical. For SECRETS the math flips: env vars are glued to the process and therefore readable in /proc/PID/environ by anyone with shell access to the host, they are inherited by child processes (including the ones that never needed them), they end up in crash dumps, in docker inspect, in support tickets copy-pasted from env. And: there is no audit log of who read which secret when, and no rotation without restarting the process.
A secret manager turns secrets into loans
Systems like HashiCorp Vault flip ownership: the service no longer OWNS a password, it BORROWS one — with its own identity (AppRole, Kubernetes service account), for a limited time, every access logged. Dynamic database credentials, generated by Vault per lease, turn rotation into steady state instead of a quarterly scramble: when the lease expires, the service fetches fresh credentials and the old password simply stops existing.
Go access to Vault goes through github.com/hashicorp/vault/api — here with AppRole login and a KV-v2 read:
// internal/secrets/vault.go — AppRole login and KV-v2 read
package secrets
import (
"context"
"fmt"
"github.com/hashicorp/vault/api"
)
func DatabasePassword(ctx context.Context, cfg Config) (string, error) {
client, err := api.NewClient(&api.Config{Address: cfg.Address})
if err != nil {
return "", err
}
// The service authenticates ITSELF — no human creds in code
login, err := client.Logical().Write("auth/approle/login", map[string]interface{}{
"role_id": cfg.RoleID,
"secret_id": cfg.SecretID,
})
if err != nil {
return "", fmt.Errorf("approle login: %w", err)
}
client.SetToken(login.Auth.ClientToken)
// KV v2: the path contains /data/ — a frequent stumbling block when migrating from v1
secret, err := client.Logical().Read("secret/data/bookstore/postgres")
if err != nil {
return "", err
}
data, _ := secret.Data["data"].(map[string]interface{})
pw, _ := data["password"].(string)
if pw == "" {
return "", fmt.Errorf("secret empty or path wrong")
}
return pw, nil
}
// Terminal: bookstore serve (startup)
// → approle login: ok (lease 2764800s) — read secret/data/bookstore/postgres ok
// → postgres password loaded: 32 chars, from Vault, never in a file
For values that must live in the repo (pipeline configuration, TLS certificates of small environments), SOPS (github.com/getsops/sops, maintained by GetSops since the Mozilla handover) is the established tool: the file stays in Git, but only the VALUES are encrypted — with age keys or cloud KMS. The structure stays diffable, merge conflicts stay readable, and review shows WHICH keys changed, just not to what:
// Terminal: workflow with SOPS + age (structure in the repo, values encrypted)
// → $ sops --encrypt --age age1… config/secrets.yaml > config/secrets.enc.yaml
// → $ git diff config/secrets.enc.yaml
// → bookstore:
// → - password: ENC[AES256_GCM,data:kQ9f…,tag:…]
// → + password: ENC[AES256_GCM,data:7mP2…,tag:…]
// → $ sops --decrypt config/secrets.enc.yaml | bookstore seed (pipeline injects)
And one more Go-side hardening measure the pentester explicitly praised: a dedicated Secret type that redacts itself when logged. The struct from lesson 59 gets an addition — and slog picks up the redaction automatically via LogValue:
// internal/config/secret.go — secrets that cannot log themselves
package config
import (
"log/slog"
"os"
)
type Secret string
func (s Secret) LogValue() slog.Value {
return slog.StringValue("[REDACTED]") // applies to Info, Warn, Error …
}
func DbPasswordFromEnv() (Secret, error) {
v, ok := os.LookupEnv("BOOKSTORE_DB_PASSWORD") // injected at runtime, never baked into images
if !ok || v == "" {
return "", ErrMissingSecret // fail fast instead of an empty string floating around
}
return Secret(v), nil
}
// Terminal: bookstore serve
// → {"level":"INFO","msg":"config loaded","addr":":8080","db_password":"[REDACTED]"}
// → (instead of, as before: "db_password":"pgSuperSecret2024" — finding 2 from the report)
⚠ Common mistake: Dumping the whole config struct into the log at startup —
logger.Info("starting", "cfg", cfg)— and wondering why the token shows up in the log stream. JSON handlers serialize every exported field; there is no Stringer panic, just plaintext. The remedy is the discipline above: wrap secrets in a dedicated type whoseLogValueonly ever yields[REDACTED], and log individual fields instead of formatting entire structs. The same discipline applies to Pod events and error messages in Kubernetes.
Check: Why are environment variables alone insufficient secrets management — the repo is clean, after all?
Answer: Because env vars leak beyond the process boundary — /proc/environ, child processes, docker inspect, crash dumps — and rotation plus access auditing are missing
The misconception reduces security to the repo. But env secrets live in the process: readable in /proc/PID/environ for anyone with host access, inherited by every child process, visible in docker inspect and crash dumps — and nobody logs read access or rotates values without a restart. The Go point in option three is true, but far from the only one — exposure is the heart of the problem.
Takeaways:
/proc/environ, docker inspect, and crash dumps, with no audit and no rotation.github.com/hashicorp/vault/api): services authenticate via AppRole, KV-v2 paths contain /data/, dynamic leases make rotation the normal state.github.com/getsops/sops) with age: values encrypted in Git, structure stays readable and diffable — good for files reviewed inside the repo.Secret type with LogValue keeps startup logs from leaking the password; fail fast on missing secrets instead of empty strings.The email arrives from the cooperative's security team: a remote code execution has been reported in a YAML parser, three levels deep in the bookstore API's dependencies. Questions in three directions: are we affected (does our code even reach the vulnerable spot)? And right next to it a second problem: the build pipeline has been breaking since the new internal module git.corp.example.com/buchhaus/lager arrived — the checksum database cannot know internal modules, and a colleague already suggests just setting GOSUMDB=off globally. Both get solved today.
The hero of the first question is govulncheck (golang.org/x/vuln/cmd/govulncheck) — the Go world's official vulnerability scanning tool. Its difference from CVE-grep scanners (which search go.sum) is the call graph: govulncheck analyzes whether your code actually calls the vulnerable SYMBOLS. A CVE in a function you never reach is not an acute finding — that filtering saves weeks of panic upgrades:
// Terminal: govulncheck — installation and run
// → $ go install golang.org/x/vuln/cmd/govulncheck@latest
// → $ govulncheck ./...
// → === Symbol Results ===
// → Vulnerability #1: GO-2026-1234 in gopkg.in/yaml.v3
// → Call stacks in your code:
// → #1: internal/pricing.loadRules → yaml.Unmarshal → …Decoder.Decode
// → Found in: gopkg.in/yaml.v3@v3.0.0
// → Fixed in: gopkg.in/yaml.v3@v3.0.1
// → Your code is affected by 1 vulnerability.
// →
// → (A second hit from go.sum — in the parser's encode path — does NOT appear: unreachable)
The second problem, internal modules: go mod tidy fails because the module can exist neither in the proxy nor in the checksum database (sum.golang.org) — it is private. The correct answer is GOPRIVATE, which carves out the private namespace in both places — from the proxy AND from checksum verification — while all public modules stay verified:
// Terminal: GOPRIVATE instead of GOSUMDB=off
// → $ go env -w GOPRIVATE=git.corp.example.com/*
// → $ git config --global url."https://oauth2:$GITLAB_TOKEN@git.corp.example.com".insteadOf "https://git.corp.example.com"
// → $ go mod tidy
// → go: downloading git.corp.example.com/buchhaus/lager v1.4.2 (straight from Git, no proxy)
// → go: verified github.com/gin-gonic/gin@v1.10.0 against sum.golang.org (still checked!)
// → $ go env GOPRIVATE
// → git.corp.example.com/*
The difference from the colleague's proposal is security-relevant: global GOSUMDB=off disables signature checking for ALL modules — a compromised mirror could slip altered public packages past you unnoticed. GOPRIVATE limits the exception to the private namespace and doubles as the default for GONOPROXY and GONOSUMDB; you can fine-tune those two individually.
Third, the inventory question: a major customer of the cooperative demands an SBOM (Software Bill of Materials) for their tender — a machine-readable manifest of all dependencies with versions and licenses. In the Go world, syft (github.com/anchore/syft) generates one as SPDX or CycloneDX; cosign (Sigstore) can additionally sign and attest it. Best of all: Go binaries carry their own inventory — embedded via runtime/debug, queryable without the original builds:
// cmd/bookstore/version.go — the binary knows its own dependencies
package main
import (
"fmt"
"runtime/debug"
)
func printSBOM() {
bi, ok := debug.ReadBuildInfo()
if !ok {
return // go run instead of go build — no build info present
}
fmt.Println("module:", bi.Main.Path, bi.Main.Version)
for _, d := range bi.Deps {
extra := ""
if d.Replace != nil {
extra = " (replace → " + d.Replace.Path + " " + d.Replace.Version + ")"
}
fmt.Println(" dep:", d.Path, d.Version+extra)
}
}
// Terminal: bookstore version
// → module: bookshop.example/kant-kurve v1.8.3
// → dep: github.com/gin-gonic/gin v1.10.0
// → dep: github.com/jackc/pgx/v5 v5.7.1
// → dep: gopkg.in/yaml.v3 v3.0.1 (the fix from finding 1 — arrived)
//
// Terminal: syft scan . -o spdx-json > sbom.spdx.json && wc -l sbom.spdx.json
// → 412 sbom.spdx.json — signed via cosign attest, attached to the image
Supply chain = inventory plus verification plus reachability
The lesson's three tools answer three questions: go.sum (plus sum.golang.org) verifies THAT a module is unaltered — GOPRIVATE excepts only what the namespace requires. govulncheck answers whether a known vulnerability is RELEVANT to you. The SBOM answers WHAT is inside you at all — the precondition for answering the next Friday-afternoon CVE email in minutes instead of days. All three together, automated in CI: govulncheck ./... nightly, SBOM attestation per release tag.
⚠ Common mistake: Because the build chokes on a private module, setting
GOSUMDB=off(and oftenGOFLAGS=-insecureon top) globally — on the dev machine AND in the CI runner. That drops checksum verification for every public module of every project on that machine: the nextgo getblindly trusts the proxy mirror. The colleague means well, but the fix needs to be surgical, not blanket-wide:GOPRIVATE=git.corp.example.com/*for exactly the private namespace, public dependencies stay signature-checked.
Check: Dependabot reports a CVE in a dependency; govulncheck reports nothing. What is the most likely explanation?
Answer: The CVE affects symbols your code never reaches (per call-graph analysis) — it is present in go.sum but not triggerable
The two tools have different views: Dependabot and friends diff go.sum against CVE databases and report EVERY affected module. govulncheck analyzes the source call graph and reports only vulnerable symbols your code actually calls. That is not an eternal all-clear — if the code changes, the spot can become reachable — but it prioritizes correctly: fix the reachable hole first.
Takeaways:
govulncheck (golang.org/x/vuln/cmd/govulncheck) filters via call-graph analysis: reachable vulnerabilities with call stacks; theoretical ones stay out.GOPRIVATE=git.corp.example.com/* exempts internal modules from proxy and sumdb duties — public modules stay verified; global GOSUMDB=off would be the chainsaw for that job.insteadOf config with a token — no credentials in go.mod.syft (github.com/anchore/syft) as SPDX/CycloneDX, signed via cosign; go version -m and runtime/debug.ReadBuildInfo read the inventory straight from the binary.Course navigation: ← Module 17 · All 20 modules · Module 19 →