{"guides":[],"hints":[{"hint":"Ask which input to Open the attacker cannot change by copying bytes between rows.","lessonID":"security.aead-encryption","nuance":"The tag covers the additional data, so opening with the victim's record ID fails authentication even though the copied ciphertext itself is intact."},{"hint":"Ask who reads argv once the new process has started.","lessonID":"security.command-injection","nuance":"Each program parses its own arguments, so a value starting with - can become a flag. -- ends option parsing in programs that support it, and validation covers those that do not."},{"hint":"Think about what happens to the response time as more of the guess is correct.","lessonID":"security.constant-time","nuance":"The result is correct; the leak is in the duration. Work that grows with the matching prefix lets an attacker recover the token one byte at a time."},{"hint":"The secret key comes from crypto/rand rather than a predictable simulation PRNG.","lessonID":"security.crypto-purposes","nuance":"No. A MAC authenticates bytes; confidentiality, expiry, replay prevention and key lifecycle require separate protocol decisions."},{"hint":"Compare what site means for cookies with what origin means for this check.","lessonID":"security.csrf-protection","nuance":"Only same-origin and none pass the Sec-Fetch-Site check; same-site and cross-site are rejected unless a trusted origin or a bypass pattern applies."},{"hint":"Two different byte strings can decode to the same value; which check compares bytes rather than values?","lessonID":"security.fuzzing-parsers","nuance":"A non-minimal varint parses without panicking and within limits, but re-encoding it yields different bytes, so only the round-trip comparison fails."},{"hint":"Think about what an attacker learns by viewing one of your pages.","lessonID":"security.http-headers","nuance":"A nonce is a bearer value: anyone who knows it can tag their own script. A fresh random value per response cannot be learned in advance or replayed later."},{"hint":"The same subject string in a different tenant is denied.","lessonID":"security.identity-authorization","nuance":"No. Validate the full credential contract, then check the principal’s permission and tenant scope for this specific resource and action."},{"hint":"Compare how a browser resolves two leading slashes with how a file path would.","lessonID":"security.open-redirects","nuance":"Two leading slashes begin a scheme-relative URL: the browser keeps the current scheme and switches to the host after the slashes. Require exactly one leading slash."},{"hint":"Upgrading needs an input that the database deliberately does not keep.","lessonID":"security.password-storage","nuance":"A password hash cannot be reversed, so only a login that has just verified the password holds the plaintext needed to hash it again with new parameters."},{"hint":"Ask what Clean and Join know about the files that actually exist.","lessonID":"security.path-traversal","nuance":"Both functions are purely lexical. A symlink inside the directory can point anywhere, so only resolution relative to an open directory, as os.Root does, is a boundary."},{"hint":"fmt reaches field values through reflection; consider which values reflection may call methods on.","lessonID":"security.secrets-redaction","nuance":"fmt cannot invoke Format, String or Error on unexported fields, so it prints their contents directly; encoding/json, by contrast, skips such fields entirely."},{"hint":"Think about who else might already know the ID that existed before login.","lessonID":"security.session-cookies","nuance":"Session fixation relies on the identifier surviving authentication. Rotating it, and deleting the old record, makes any copy obtained before login worthless."},{"hint":"Think about where in the SQL grammar a parameter is allowed to appear.","lessonID":"security.sql-injection","nuance":"A parameter is always a value. ORDER BY $1 either fails or sorts by a constant, so the column must come from a fixed map in code and every other key is rejected."},{"hint":"The attacker-shaped string stays inside a query parameter on the configured example domain.","lessonID":"security.ssrf-egress","nuance":"No. Each redirect and actual connection must satisfy the egress policy; fixed configured destinations reduce the attack surface."},{"hint":"The database is a transparent log of hashes; think about what a hash can and cannot say about code.","lessonID":"security.supply-chain","nuance":"The checksum database makes content tampering and per-user substitution detectable; whether the published code is safe still needs review and govulncheck."},{"hint":"The httptest client trusts its associated test certificate without setting InsecureSkipVerify.","lessonID":"security.tls-trust","nuance":"No. Supply the intended test or private trust relationship and verify the expected peer; keep chain and hostname verification in production."},{"hint":"Consider who wrote the header and what they would choose.","lessonID":"security.token-design","nuance":"The header is attacker-controlled input. Honoring it enables alg none and key-confusion attacks, so the expected algorithm must come from configuration bound to the key."},{"hint":"Look at the scheme of the value the user saved, not at its characters.","lessonID":"security.xss-templates","nuance":"The URL filter passes relative URLs and http, https and mailto. A javascript: or data: value is replaced with an inert marker instead of being escaped."}],"id":"security","labs":[],"practice":{"bugs":[],"drills":[],"interviews":[],"quizzes":[],"reviewPairs":[],"reviewRounds":[]},"readings":[{"conceptTag":"security.identity-authorization","designGuide":{"cautions":["Do not trust roles or tenant IDs copied from unverified headers or an unverified token payload.","Run native service and failure tests in your own development environment."],"cost":"Additional state and tests must be justified by the demonstrated failure; this lesson is not a requirement for every Go program.","family":"security","flow":["Verify credential","Construct principal","Load scoped resource","Authorize action"],"ratings":[],"strengths":["Validate identity separately from permission to act on a particular resource.","Makes the owner and the failure boundary explicit."]},"hint":"The same subject string in a different tenant is denied.","id":"security.identity-authorization","introduction":"A signed token can be genuine and still belong to the wrong audience, issuer or operation. Even a fully valid token does not prove that its subject may read a particular order. Treat authentication as construction of a verified principal and authorization as an explicit resource-scoped decision. Fail closed when either contract is missing rather than accepting whatever identity-shaped value a request provides.","nuance":"No. Validate the full credential contract, then check the principal’s permission and tenant scope for this specific resource and action.","objective":"Validate identity separately from permission to act on a particular resource.","question":"A JWT signature is valid. May its subject automatically read any order ID?","references":["https://github.com/golang-jwt/jwt","https://pkg.go.dev/net/http","https://www.rfc-editor.org/rfc/rfc8725"],"reviewAnswer":"Verify principal, then authorize this resource","reviewPrompt":"Authentication + authorization","sections":[{"body":"A signed token can be genuine and still belong to the wrong audience, issuer or operation. Even a fully valid token does not prove that its subject may read a particular order. Treat authentication as construction of a verified principal and authorization as an explicit resource-scoped decision. Fail closed when either contract is missing rather than accepting whatever identity-shaped value a request provides.","title":"The contract and the failure"},{"body":"With JWT, use a maintained verifier, constrain acceptable algorithms and validate key selection, issuer, audience, expiry and other required claims. Parsing or base64-decoding is not verification. Design key rotation and revocation/session policies. For browser clients, choose cookie/CSRF/CORS rules deliberately; CORS is not an authorization mechanism for non-browser callers.","code":"package main\n\nimport \"fmt\"\n\ntype Principal struct{ Subject, Tenant, Role string }\ntype Document struct{ Tenant, Owner string }\n\nfunc canRead(p Principal, d Document) bool {\n\treturn p.Subject != \"\" && p.Tenant == d.Tenant && (p.Subject == d.Owner || p.Role == \"auditor\")\n}\nfunc main() {\n\t// These are already-verified test principals, not values read from headers.\n\td := Document{Tenant: \"a\", Owner: \"user-1\"}\n\tfmt.Println(canRead(Principal{\"user-1\", \"a\", \"reader\"}, d)) // true\n\tfmt.Println(canRead(Principal{\"user-1\", \"b\", \"reader\"}, d)) // false\n}","language":"go","title":"Work through the example","walkthrough":"The same subject string in a different tenant is denied. This pure function models authorization after authentication; it deliberately does not parse or verify a JWT. Construct the principal only after the authentication layer validates the chosen credential, and test resource rules independently of token parsing."},{"body":"Do not trust roles or tenant IDs copied from unverified headers or an unverified token payload. Avoid returning a different secret-laden error body for every verification failure. Test wrong issuer/audience, expired and not-yet-valid credentials, unknown keys, missing required claims and a valid credential attempting another tenant’s resource. These are native service lessons, not registration or accounts added to GopherForge.","title":"Production decisions"},{"body":"A JWT signature is valid. May its subject automatically read any order ID? No. Validate the full credential contract, then check the principal’s permission and tenant scope for this specific resource and action. Describe the state before the operation, its owner, the failure between steps and the evidence you would test. Distinguish what this example demonstrates from the infrastructure a production service still needs.","title":"Explain it in an interview"}],"takeaway":"Validate identity separately from permission to act on a particular resource. No. Validate the full credential contract, then check the principal’s permission and tenant scope for this specific resource and action.","title":"Authentication and authorization: a verified token is only the beginning","unitID":"security","wrongAnswers":["Base64-decoding proves a JWT signature","A valid signature authorizes every resource"]},{"conceptTag":"security.crypto-purposes","designGuide":{"cautions":["Do not use math/rand for secrets, a fast unsalted digest for password storage, or a plain equality loop for secret MAC tags.","Run native service and failure tests in your own development environment."],"cost":"Additional state and tests must be justified by the demonstrated failure; this lesson is not a requirement for every Go program.","family":"security","flow":["Define purpose","Use reviewed primitive","Manage key + cost","Test hostile inputs"],"ratings":[],"strengths":["Choose purpose-specific primitives and bound their cost instead of inventing cryptography.","Makes the owner and the failure boundary explicit."]},"hint":"The secret key comes from crypto/rand rather than a predictable simulation PRNG.","id":"security.crypto-purposes","introduction":"A fast hash, password hash, MAC, encryption scheme and digital signature answer different questions. A SHA-256 digest does not make a password database resistant to guessing, and encryption without authentication can accept altered ciphertext. Use reviewed libraries and document the purpose, key lifetime, input format and resource budget before selecting a primitive.","nuance":"No. A MAC authenticates bytes; confidentiality, expiry, replay prevention and key lifecycle require separate protocol decisions.","objective":"Choose purpose-specific primitives and bound their cost instead of inventing cryptography.","question":"Which distinction must be made before choosing a cryptographic primitive?","references":["https://pkg.go.dev/crypto/hmac","https://pkg.go.dev/crypto/rand","https://pkg.go.dev/golang.org/x/crypto/argon2"],"reviewAnswer":"Password KDF, MAC, encryption and signature differ","reviewPrompt":"Cryptographic purpose","sections":[{"body":"A fast hash, password hash, MAC, encryption scheme and digital signature answer different questions. A SHA-256 digest does not make a password database resistant to guessing, and encryption without authentication can accept altered ciphertext. Use reviewed libraries and document the purpose, key lifetime, input format and resource budget before selecting a primitive.","title":"The contract and the failure"},{"body":"Use an appropriate reviewed password KDF such as Argon2id where your policy permits it, with random salt and stored algorithm/version/cost parameters. Benchmark memory and CPU cost under concurrent login load and bound admission; expensive verification is also a denial-of-service surface. For secret encryption prefer a reviewed authenticated construction and a key/nonce management design instead of assembling low-level primitives.","code":"package main\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"fmt\"\n)\n\nfunc tag(key, message []byte) []byte {\n\tm := hmac.New(sha256.New, key)\n\t_, _ = m.Write(message)\n\treturn m.Sum(nil)\n}\nfunc main() {\n\tkey := make([]byte, 32)\n\tif _, err := rand.Read(key); err != nil {\n\t\tpanic(err)\n\t}\n\tmessage := []byte(\"action=read;resource=7\")\n\texpected := tag(key, message)\n\tfmt.Println(hmac.Equal(expected, tag(key, message)))                           // true\n\tfmt.Println(hmac.Equal(expected, tag(key, []byte(\"action=write;resource=7\")))) // false\n\t// Never print key material; a MAC does not hide the message.\n}","language":"go","title":"Work through the example","walkthrough":"The secret key comes from crypto/rand rather than a predictable simulation PRNG. HMAC authenticates these exact bytes and hmac.Equal performs the intended tag comparison. This example has no expiry, replay store or message canonicalization policy, so it is not by itself a complete access-token protocol."},{"body":"Do not use math/rand for secrets, a fast unsalted digest for password storage, or a plain equality loop for secret MAC tags. Do not copy one parameter value forever from a tutorial. Test corrupted tags, wrong keys, duplicate/replayed messages, unsupported KDF parameters and resource exhaustion. Keep production keys outside code and logs, and define rotation and recovery procedures.","title":"Production decisions"},{"body":"Does an HMAC both hide its message and prevent the same message being replayed? No. A MAC authenticates bytes; confidentiality, expiry, replay prevention and key lifecycle require separate protocol decisions. Describe the state before the operation, its owner, the failure between steps and the evidence you would test. Distinguish what this example demonstrates from the infrastructure a production service still needs.","title":"Explain it in an interview"}],"takeaway":"Choose purpose-specific primitives and bound their cost instead of inventing cryptography. No. A MAC authenticates bytes; confidentiality, expiry, replay prevention and key lifecycle require separate protocol decisions.","title":"Passwords, MACs and randomness solve different problems","unitID":"security","wrongAnswers":["A fast digest is a password storage policy","A valid MAC encrypts and expires a message"]},{"conceptTag":"security.ssrf-egress","designGuide":{"cautions":["A domain allowlist does not protect a compromised allowed service from returning hostile data, and a URL parser does not establish permission.","Run native service and failure tests in your own development environment."],"cost":"Additional state and tests must be justified by the demonstrated failure; this lesson is not a requirement for every Go program.","family":"security","flow":["Choose configured upstream","Encode user data","Enforce redirect + dial policy","Bound response and time"],"ratings":[],"strengths":["Keep outbound destinations controlled and validate redirects and connection-time policy.","Makes the owner and the failure boundary explicit."]},"hint":"The attacker-shaped string stays inside a query parameter on the configured example domain.","id":"security.ssrf-egress","introduction":"A URL supplied by a user can target internal services, metadata endpoints or a different host after redirection. Checking that the string begins with https is insufficient. Prefer a small configured set of upstream services and let user input select a resource within one of them. When arbitrary destinations are a real requirement, enforce address and egress policy at connection time as well as during URL parsing.","nuance":"No. Each redirect and actual connection must satisfy the egress policy; fixed configured destinations reduce the attack surface.","objective":"Keep outbound destinations controlled and validate redirects and connection-time policy.","question":"Which principle must govern an initial outbound URL and every redirect target?","references":["https://pkg.go.dev/net/http#Client","https://pkg.go.dev/net/url","https://owasp.org/www-community/attacks/Server_Side_Request_Forgery"],"reviewAnswer":"User data is not authority to choose a host","reviewPrompt":"Outbound destination control","sections":[{"body":"A URL supplied by a user can target internal services, metadata endpoints or a different host after redirection. Checking that the string begins with https is insufficient. Prefer a small configured set of upstream services and let user input select a resource within one of them. When arbitrary destinations are a real requirement, enforce address and egress policy at connection time as well as during URL parsing.","title":"The contract and the failure"},{"body":"Use an owned http.Client with explicit time and response-size budgets. Disable automatic redirects or revalidate every hop under the same policy. Consider userinfo, ports, IP literals, IPv6, alternate encodings and DNS resolution/rebinding. A reviewed dialer or infrastructure egress control must enforce forbidden internal ranges against the actual connection target; validating a hostname once before a later independent DNS lookup is not enough.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"net/url\"\n)\n\nfunc profileURL(id string) string {\n\tbase := url.URL{Scheme: \"https\", Host: \"api.vendor.example\", Path: \"/profiles\"}\n\tq := url.Values{}\n\tq.Set(\"id\", id)\n\tbase.RawQuery = q.Encode()\n\treturn base.String()\n}\nfunc main() {\n\tfmt.Println(profileURL(\"http://127.0.0.1/admin\"))\n\t// The untrusted value is an encoded query value, never the destination host.\n}","language":"go","title":"Work through the example","walkthrough":"The attacker-shaped string stays inside a query parameter on the configured example domain. The code does not send a request and does not claim the upstream application is safe from injection. Its narrower guarantee is that this input cannot select the network host or scheme."},{"body":"A domain allowlist does not protect a compromised allowed service from returning hostile data, and a URL parser does not establish permission. Do not follow a redirect into a forbidden host or log upstream credentials in the URL. Test fixed-destination behavior, hostile resource IDs, redirects, private addresses, changed DNS answers and decompressed response limits in an isolated native environment.","title":"Production decisions"},{"body":"An allowed public URL redirects to a private address. May a client follow it without rechecking policy? No. Each redirect and actual connection must satisfy the egress policy; fixed configured destinations reduce the attack surface. Describe the state before the operation, its owner, the failure between steps and the evidence you would test. Distinguish what this example demonstrates from the infrastructure a production service still needs.","title":"Explain it in an interview"}],"takeaway":"Keep outbound destinations controlled and validate redirects and connection-time policy. No. Each redirect and actual connection must satisfy the egress policy; fixed configured destinations reduce the attack surface.","title":"SSRF: let user input choose data, not an arbitrary network destination","unitID":"security","wrongAnswers":["An https prefix prevents SSRF","Validate the first URL and trust all redirects"]},{"conceptTag":"security.tls-trust","designGuide":{"cautions":["Do not solve certificate failures by setting InsecureSkipVerify or by accepting every certificate in a callback.","Run native service and failure tests in your own development environment."],"cost":"Additional state and tests must be justified by the demonstrated failure; this lesson is not a requirement for every Go program.","family":"security","flow":["Choose expected peer","Configure controlled trust","Verify chain + name","Test rotation and failures"],"ratings":[],"strengths":["Keep certificate-chain and hostname verification while making trust and rotation explicit.","Makes the owner and the failure boundary explicit."]},"hint":"The httptest client trusts its associated test certificate without setting InsecureSkipVerify.","id":"security.tls-trust","introduction":"A TLS connection can encrypt traffic to the wrong peer if verification is disabled. Certificate chain trust and hostname identity both matter; changing a boolean until a development request succeeds can silently remove production authentication. Use a deliberate trust store, keep the expected server identity tied to the configured destination and handle private development certificates through a separate test trust configuration.","nuance":"No. Supply the intended test or private trust relationship and verify the expected peer; keep chain and hostname verification in production.","objective":"Keep certificate-chain and hostname verification while making trust and rotation explicit.","question":"A development endpoint has an untrusted certificate. Is disabling verification a production fix?","references":["https://pkg.go.dev/crypto/tls#Config","https://pkg.go.dev/net/http/httptest#Server.Client","https://go.dev/doc/security/"],"reviewAnswer":"Validate chain and hostname; control trust roots","reviewPrompt":"TLS peer verification","sections":[{"body":"A TLS connection can encrypt traffic to the wrong peer if verification is disabled. Certificate chain trust and hostname identity both matter; changing a boolean until a development request succeeds can silently remove production authentication. Use a deliberate trust store, keep the expected server identity tied to the configured destination and handle private development certificates through a separate test trust configuration.","title":"The contract and the failure"},{"body":"Use current platform Go defaults and the deployment’s reviewed minimum TLS policy. Configure private roots through a controlled CA process and test hostname mismatches, expired certificates and rotation. For mTLS, define both certificate verification and application authorization for the resulting identity. Plan long-lived connection behavior during rotation and shutdown.","code":"package main\n\nimport (\n\t\"crypto/tls\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"time\"\n)\n\nfunc main() {\n\tserver := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(\"ok\")) }))\n\tdefer server.Close()\n\t// This test helper trusts only its own test server certificate.\n\tclient := server.Client()\n\tclient.Timeout = 2 * time.Second\n\tconfig := client.Transport.(*http.Transport).TLSClientConfig\n\tfmt.Println(config.InsecureSkipVerify == false)\n\tresp, err := client.Get(server.URL)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer resp.Body.Close()\n\tfmt.Println(resp.StatusCode, resp.TLS.Version >= tls.VersionTLS12)\n}","language":"go","title":"Work through the example","walkthrough":"The httptest client trusts its associated test certificate without setting InsecureSkipVerify. It demonstrates a scoped native test trust relationship, not a reason to ship that test certificate or trust arbitrary self-signed endpoints. The last check inspects this local test connection’s negotiated TLS version; it does not describe a public endpoint’s configuration."},{"body":"Do not solve certificate failures by setting InsecureSkipVerify or by accepting every certificate in a callback. TLS does not validate a JSON payload, authorize an object or remove SSRF risk. Keep signing keys and token material out of telemetry. Test a wrong hostname, untrusted root, expired certificate, unavailable revocation/rotation dependencies and the operational recovery path.","title":"Production decisions"},{"body":"A development endpoint has an untrusted certificate. Is disabling verification a production fix? No. Supply the intended test or private trust relationship and verify the expected peer; keep chain and hostname verification in production. Describe the state before the operation, its owner, the failure between steps and the evidence you would test. Distinguish what this example demonstrates from the infrastructure a production service still needs.","title":"Explain it in an interview"}],"takeaway":"Keep certificate-chain and hostname verification while making trust and rotation explicit. No. Supply the intended test or private trust relationship and verify the expected peer; keep chain and hostname verification in production.","title":"TLS: verify the peer instead of disabling the error","unitID":"security","wrongAnswers":["Encryption makes peer verification unnecessary","InsecureSkipVerify is a production certificate fix"]},{"conceptTag":"security.sql-injection","designGuide":{"cautions":["Raw-SQL methods in ORMs and query builders reintroduce concatenation.","A bound LIKE, regex or full-text value is still interpreted by its operator."],"cost":"Almost nothing at run time; the cost is review discipline and a small allow-list map for every dynamic identifier.","family":"security","flow":["Keep statement constant","Bind values as args","Allow-list identifiers","Escape LIKE wildcards"],"ratings":[],"strengths":["The database never parses user input as SQL syntax.","Constant statements are easy to review, grep and prepare once."]},"hint":"Think about where in the SQL grammar a parameter is allowed to appear.","id":"security.sql-injection","introduction":"SQL injection happens when a value supplied by a user becomes part of the statement the database parses. database/sql gives you a second channel: the query text reaches the driver as one string and every argument travels beside it as a typed value. The SQL rows lesson stated that placeholders bind values, not grammar; this lesson makes that separation visible with a recording driver and covers the places where binding alone is not enough: identifiers, sort direction and LIKE patterns.","nuance":"A parameter is always a value. ORDER BY $1 either fails or sorts by a constant, so the column must come from a fixed map in code and every other key is rejected.","objective":"Send untrusted values as database/sql arguments, pick identifiers from allow-lists in code and escape LIKE wildcards with an explicit ESCAPE clause.","question":"A list endpoint lets clients choose the sort column. Why does a placeholder not solve the injection risk?","references":["https://go.dev/doc/database/sql-injection","https://pkg.go.dev/database/sql/driver#QueryerContext","https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html","https://www.postgresql.org/docs/current/functions-matching.html"],"reviewAnswer":"Placeholders bind values, not identifiers or keywords","reviewPrompt":"Placeholder for a sort column?","sections":[{"body":"Build a statement with + or fmt.Sprintf and the database receives one string. It cannot know which characters came from your code and which came from a form field, so a name such as x' OR '1'='1 closes the string literal and appends a condition that is always true. Escaping quotes by hand looks like a fix until a different character set, a backslash rule or a numeric position that needs no quotes at all defeats it. The durable fix is structural: keep the statement constant and pass values through the driver's parameter mechanism, so a value never passes through the SQL parser as syntax. Placeholder syntax belongs to the driver, not to database/sql: PostgreSQL drivers use $1, $2 and so on, while MySQL and SQLite drivers use ?.","title":"Concatenation hands the parser your user's syntax"},{"body":"A database driver implements a few interfaces from database/sql/driver. This program registers a tiny fake whose connection implements QueryerContext: database/sql calls it with the query string and a slice of driver.NamedValue, and the fake prints both instead of contacting a server. Four calls show a concatenated statement, a parameterized one, an allow-listed ORDER BY and a LIKE search for text that itself contains wildcard characters.","code":"package main\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"database/sql/driver\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n)\n\n// recordingDriver is a test double: it prints what database/sql hands to a\n// driver and returns no rows. A real driver sends the same two parts to the\n// database server.\ntype recordingDriver struct{}\n\nfunc (recordingDriver) Open(string) (driver.Conn, error) { return conn{}, nil }\n\ntype conn struct{}\n\nfunc (conn) Prepare(string) (driver.Stmt, error) { return nil, errors.New(\"prepare not supported\") }\nfunc (conn) Close() error                        { return nil }\nfunc (conn) Begin() (driver.Tx, error)           { return nil, errors.New(\"transactions not supported\") }\n\n// QueryContext receives the SQL text and the arguments as separate values.\nfunc (conn) QueryContext(_ context.Context, query string, args []driver.NamedValue) (driver.Rows, error) {\n\tvals := make([]string, len(args))\n\tfor i, a := range args {\n\t\tvals[i] = fmt.Sprintf(\"$%d=%T(%#v)\", a.Ordinal, a.Value, a.Value)\n\t}\n\tfmt.Printf(\"  sql:  %s\\n  args: [%s]\\n\", query, strings.Join(vals, \" \"))\n\treturn emptyRows{}, nil\n}\n\ntype emptyRows struct{}\n\nfunc (emptyRows) Columns() []string         { return []string{\"id\"} }\nfunc (emptyRows) Close() error              { return nil }\nfunc (emptyRows) Next([]driver.Value) error { return io.EOF }\n\n// sortColumns maps a public sort key to a fixed SQL fragment.\nvar sortColumns = map[string]string{\n\t\"name\":   \"name ASC\",\n\t\"newest\": \"created_at DESC\",\n}\n\n// likeEscaper makes %, _ and the escape character itself literal.\nvar likeEscaper = strings.NewReplacer(\"!\", \"!!\", \"%\", \"!%\", \"_\", \"!_\")\n\nfunc run(ctx context.Context, db *sql.DB, query string, args ...any) {\n\trows, err := db.QueryContext(ctx, query, args...)\n\tif err != nil {\n\t\tfmt.Println(\"  error:\", err)\n\t\treturn\n\t}\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t}\n\tif err := rows.Err(); err != nil {\n\t\tfmt.Println(\"  error:\", err)\n\t}\n}\n\nfunc main() {\n\tsql.Register(\"recorder\", recordingDriver{})\n\tdb, err := sql.Open(\"recorder\", \"\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer db.Close()\n\tctx := context.Background()\n\tname := \"x' OR '1'='1\"\n\n\tfmt.Println(\"concatenated (vulnerable):\")\n\trun(ctx, db, \"SELECT id FROM users WHERE name = '\"+name+\"'\")\n\n\tfmt.Println(\"parameterized:\")\n\trun(ctx, db, \"SELECT id FROM users WHERE name = $1\", name)\n\n\tfmt.Println(\"allow-listed ORDER BY:\")\n\tfor _, key := range []string{\"newest\", \"name; DROP TABLE users\"} {\n\t\torder, ok := sortColumns[key]\n\t\tif !ok {\n\t\t\tfmt.Printf(\"  rejected sort key %q\\n\", key)\n\t\t\tcontinue\n\t\t}\n\t\trun(ctx, db, \"SELECT id FROM users ORDER BY \"+order+\" LIMIT $1\", 20)\n\t}\n\n\tfmt.Println(\"LIKE with escaped wildcards:\")\n\tpattern := \"%\" + likeEscaper.Replace(\"50%_off!\") + \"%\"\n\trun(ctx, db, \"SELECT id FROM products WHERE title LIKE $1 ESCAPE '!'\", pattern)\n}","language":"go","title":"Record what database/sql actually hands the driver","walkthrough":"In the first call the attacker's quote marks are inside the sql line and args is empty: the OR clause is now part of the statement. In the second call the statement is constant and the same characters arrive as a string argument bound to $1, so the database compares name with that exact string. database/sql converts each argument to a driver.Value before the driver sees it, which is why the untyped 20 arrives as int64. The sort key is looked up in a map of fixed SQL fragments, so the hostile key never reaches the driver at all. The LIKE pattern is still an argument, but its % and _ were escaped with ! first and the statement declares ESCAPE '!'. The fake parses nothing; it models the interface boundary, not database behavior."},{"body":"A placeholder can stand only where the grammar expects a value. Table names, column names, ASC and DESC are part of the statement's structure, so a database either rejects ORDER BY $1 or sorts every row by the same constant value, which silently does nothing. When a request legitimately chooses among columns, map public keys such as newest or name to SQL fragments written in your code, reject anything else with a 400 and keep the map next to the query so a reviewer sees the complete set. The same rule covers table names chosen for partitioning or tenancy: take them from configuration you own, never from the request. IN lists are the other common case: generate one placeholder per element from the count, and pass the elements as arguments.","code":"// placeholders(3) == \"$1, $2, $3\"; the values themselves stay in args.\nfunc placeholders(n int) string {\n\tparts := make([]string, n)\n\tfor i := range parts {\n\t\tparts[i] = \"$\" + strconv.Itoa(i+1)\n\t}\n\treturn strings.Join(parts, \", \")\n}\n\nfunc postsByID(ctx context.Context, db *sql.DB, ids []int64) (*sql.Rows, error) {\n\tif len(ids) == 0 || len(ids) > 500 {\n\t\treturn nil, errors.New(\"between 1 and 500 ids\")\n\t}\n\tquery := \"SELECT id, title FROM posts WHERE id IN (\" + placeholders(len(ids)) + \")\"\n\targs := make([]any, len(ids))\n\tfor i, id := range ids {\n\t\targs[i] = id\n\t}\n\treturn db.QueryContext(ctx, query, args...)\n}","language":"go","title":"Identifiers and keywords need an allow-list, not a placeholder","walkthrough":"This fragment runs in your own service against a real PostgreSQL driver. The SQL text is built only from a number your code controls, so this concatenation is safe; every id still travels as an argument. The empty-list check matters because IN () is a syntax error, and the upper bound matters because every database limits how many parameters one statement may carry. Drivers that encode slices can bind a whole array instead, as in id = ANY($1) with PostgreSQL."},{"body":"Binding a search term stops injection into the statement, but LIKE interprets the bound value: % matches any run of characters and _ matches exactly one. A user searching for 100% or snake_case gets wrong results, and a pattern that begins with % cannot use an ordinary B-tree index, so a public search box needs length and rate limits anyway. Escape the wildcards and the escape character itself, then name that character in an ESCAPE clause instead of relying on a default: PostgreSQL and MySQL default to backslash, SQLite has none, and in MySQL a backslash inside a string literal is itself an escape, which is why the example uses !. Treat other embedded languages the same way: regular expressions, full-text query syntax and JSON path expressions accept operators inside a bound value, so validate their size and shape too.","title":"A bound LIKE pattern is still a small language"},{"body":"Most real injections in Go services come through escape hatches. Query builders and ORMs offer raw-SQL methods for ORDER BY, WHERE fragments and JSON operators, and a fmt.Sprintf passed to one of them is exactly as dangerous as concatenating in db.QueryContext. Second-order injection is the delayed version: a value is stored safely through a parameter, then a reporting job or migration reads it back and splices it into dynamic SQL, trusting it because it came from your own database. Stored procedures that assemble EXECUTE strings move the problem into SQL instead of removing it. Some drivers can be configured to interpolate arguments on the client rather than using server-side parameters, which shifts escaping into the driver; keep the default unless you have measured a reason. Finally, limit the blast radius: the application's database role should not own the schema or read tables it never queries.","title":"Where injection survives in code that uses placeholders"},{"body":"In review, look at every QueryContext, ExecContext and QueryRowContext call and ask whether its query argument is a constant or is assembled only from fragments your code owns. Static analysis helps: gosec reports SQL built with string formatting or concatenation (rules G201 and G202). In tests, send hostile values such as quotes, semicolons, comment markers and wildcard characters through the real queries against a disposable database and assert on the rows returned, not merely on the absence of an error. A recording driver like the one above is useful in unit tests to assert that a function sends a constant statement and exactly the expected arguments.","title":"Review and test the boundary"}],"takeaway":"Keep every statement constant and pass untrusted values as arguments; choose identifiers and sort order from an allow-list in code, and escape LIKE wildcards with an explicit ESCAPE clause.","title":"SQL injection: the query text and the user's values must reach the driver separately","unitID":"security-web","wrongAnswers":["Bound column names are quoted, so ORDER BY $1 sorts safely","Escaping quotes in the sort key makes concatenation safe"]},{"conceptTag":"security.xss-templates","designGuide":{"cautions":["template.HTML, JS and URL conversions disable escaping without checking anything.","Frontend code that uses innerHTML is outside html/template's protection."],"cost":"Templates must be valid, analyzable HTML and rich user content needs a separate sanitizer; the escaping itself is cheap.","family":"security","flow":["Parse trusted template","Pass untrusted data","Escape per context","Review typed content"],"ratings":[],"strengths":["The escaper follows text, attribute, URL, JS and CSS contexts automatically.","Unsafe URL schemes are neutralized instead of rendered as clickable links."]},"hint":"Look at the scheme of the value the user saved, not at its characters.","id":"security.xss-templates","introduction":"Cross-site scripting happens when data from one user becomes markup or script in another user's browser. Escaping is the defense, but the correct escaping depends on where a value lands: a text node, a quoted attribute, a URL, a JavaScript string and a CSS value each have different metacharacters. Go's html/template parses your template, tracks that context at every action and applies the matching escaper automatically. text/template does none of this, and typed strings such as template.HTML tell html/template to stop.","nuance":"The URL filter passes relative URLs and http, https and mailto. A javascript: or data: value is replaced with an inert marker instead of being escaped.","objective":"Render untrusted data with html/template, read its context-specific escaping and treat every typed-content conversion as a reviewed trust decision.","question":"A profile page renders a user's website link as href=\"#ZgotmplZ\". What happened?","references":["https://pkg.go.dev/html/template","https://pkg.go.dev/html/template#HTML","https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html"],"reviewAnswer":"Unsafe content reached a URL or CSS context","reviewPrompt":"What does #ZgotmplZ in HTML mean?","sections":[{"body":"Take a display name such as <img src=x onerror=alert(1)>. In a text node its angle brackets must be entity-encoded. In a quoted attribute the quote character matters most. Inside a <script> block HTML entities mean nothing, so the value must become a correctly escaped JavaScript string. In an href the danger is not a character at all but the scheme: a javascript: URL runs code when clicked. An escaping function that is right for one of these contexts is wrong for another, which is why calling html.EscapeString on everything and concatenating strings is not a defense. The engine that writes the page has to know where each value is going.","title":"One payload, four different meanings"},{"body":"The program parses one template text with both packages and executes it with the same hostile data: a name carrying an event-handler payload, a javascript: link, a search query with spaces and an ampersand, and a staff-written biography typed as template.HTML. Comparing the two outputs line by line shows what html/template decided in each context.","code":"package main\n\nimport (\n\t\"fmt\"\n\thtmltemplate \"html/template\"\n\t\"strings\"\n\ttexttemplate \"text/template\"\n)\n\nconst page = `<p title=\"{{.Name}}\">Hi {{.Name}}</p>\n<a href=\"{{.Site}}\">home</a> <a href=\"/search?q={{.Query}}\">find</a>\n<script>const user = {{.Name}};</script>\n<div>{{.Bio}}</div>`\n\ntype profile struct {\n\tName  string\n\tSite  string\n\tQuery string\n\tBio   htmltemplate.HTML // a trust assertion: rendered without escaping\n}\n\nfunc main() {\n\tdata := profile{\n\t\tName:  `<img src=x onerror=alert(1)>`,\n\t\tSite:  \"javascript:alert(document.cookie)\",\n\t\tQuery: \"go & rust\",\n\t\tBio:   htmltemplate.HTML(`<b>written by staff</b>`),\n\t}\n\n\tvar unsafe strings.Builder\n\tt := texttemplate.Must(texttemplate.New(\"page\").Parse(page))\n\tif err := t.Execute(&unsafe, data); err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(\"text/template:\")\n\tfmt.Println(unsafe.String())\n\n\tvar safe strings.Builder\n\th := htmltemplate.Must(htmltemplate.New(\"page\").Parse(page))\n\tif err := h.Execute(&safe, data); err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(\"html/template:\")\n\tfmt.Println(safe.String())\n}","language":"go","title":"Render the same data with text/template and html/template","walkthrough":"text/template copies every value verbatim: the image tag would run in the paragraph, a payload containing a double quote would break out of the title attribute, and the script block becomes invalid JavaScript containing markup. html/template entity-encodes the name in both the text node and the attribute. In the first href it inspects the scheme, refuses javascript: and substitutes #ZgotmplZ, a deliberately meaningless marker. In the query string it percent-encodes the value, so & cannot start a new parameter. Inside <script> it emits a quoted JavaScript string with < and > written as \\u003c and \\u003e, so the browser never sees a tag. The Bio line is identical in both outputs because template.HTML told html/template the value is already safe markup."},{"body":"ZgotmplZ is the innocuous word html/template emits when an unsafe value reaches a URL, CSS or attribute-name position at run time. In URL attributes the filter passes relative references and the http, https and mailto schemes; javascript:, data: and every other scheme become #ZgotmplZ. Seeing it in rendered HTML means the data and the template disagree about what is allowed, so fix the data or the design instead of reaching for a conversion. html/template also refuses templates it cannot analyze: a template that ends inside an unclosed tag or attribute, an action in an ambiguous part of a URL, or if branches that leave the parser in different contexts make Execute return an error. Treat those errors as defects caught before any browser saw the page.","title":"#ZgotmplZ is a refusal, not a bug to silence"},{"body":"html/template skips escaping for values of type template.HTML, HTMLAttr, URL, JS, JSStr, CSS and Srcset in their matching contexts. The conversion checks nothing; it is a claim, made by whoever wrote it, that the string is already safe there. That claim is correct for markup your own code generated, for the output of another executed template and for the output of a maintained HTML sanitizer. It is wrong for user input, for rows another service wrote, for Markdown rendered without sanitizing and for JSON pasted into a script as template.JS. Keep conversions rare, next to the code that produced the value and easy to search for, so a reviewer can list every place the escaper is switched off.","code":"// Reviewable: the conversion sits next to the sanitizer that justifies it.\nfunc renderBio(markdown string) template.HTML {\n\tunsafeHTML := markdownToHTML(markdown) // may contain <script>\n\treturn template.HTML(policy.Sanitize(unsafeHTML))\n}\n\n// Dangerous: a trust assertion about data nobody checked.\ndata := map[string]any{\"Bio\": template.HTML(r.FormValue(\"bio\"))}","language":"go","title":"Typed content is a trust assertion","walkthrough":"This fragment runs in your own service; markdownToHTML and policy stand for a Markdown renderer and an allow-list HTML sanitizer such as bluemonday, neither of which is in the standard library. The first function keeps the conversion beside the sanitizer that justifies it. The last line is the pattern to search for in review: a request value converted to template.HTML reintroduces exactly the XSS that html/template was preventing."},{"body":"html/template assumes the template text is trusted and only the data is not, so never parse a template from user input. Its guarantees end at the HTML it writes. A JSON API whose data the frontend inserts with innerHTML is DOM-based XSS, and the fix lives in that JavaScript. A handler that writes user bytes with w.Write or Gin's c.Data and a text/html content type bypasses templates entirely, and an uploaded file served from your origin needs a correct Content-Type plus X-Content-Type-Options: nosniff, ideally from a separate download domain. In Gin, c.HTML renders through html/template, so templates loaded with LoadHTMLGlob get contextual escaping, while c.String responds as text/plain. A Content-Security-Policy, covered in the headers lesson, is the second layer for the day an escaping decision goes wrong.","title":"What html/template does not cover"},{"body":"In review, look for text/template imports in packages that produce HTML, for template.HTML, JS and URL conversions, and for handlers that set Content-Type to text/html by hand. In tests, render each template with a fixed set of hostile values: angle brackets, both quote characters, a javascript: URL and a closing </script>. Assert on the exact output, as the program prints it, so an edit that moves an action into a new context shows up as a diff. A golden-file test per template is cheap and catches the regression a human reviewer is least likely to notice.","title":"Review and test escaping"}],"takeaway":"Render HTML only with html/template, let it choose the escaper for each context, and treat every template.HTML, JS or URL conversion as a reviewed claim that the value is already safe.","title":"html/template escapes by context, and template.HTML is where that protection switches off","unitID":"security-web","wrongAnswers":["html/template could not parse the URL syntax","The value was percent-encoded beyond recognition"]},{"conceptTag":"security.csrf-protection","designGuide":{"cautions":["GET, HEAD and OPTIONS always pass, so they must never change state.","Requests without Sec-Fetch-Site and Origin are allowed as non-browser clients."],"cost":"One wrapper at startup; the ongoing cost is keeping GET handlers free of side effects and reviewing every bypass pattern.","family":"security","flow":["Allow safe methods","Read Sec-Fetch-Site","Fall back to Origin","Apply exemptions"],"ratings":[],"strengths":["No per-session token state and no changes to forms are required.","One wrapper protects every route, including routes added later."]},"hint":"Compare what site means for cookies with what origin means for this check.","id":"security.csrf-protection","introduction":"Cross-site request forgery abuses ambient credentials. A page on another site submits a form or calls fetch toward your service, the browser attaches your session cookie, and your handler sees an authenticated request it never meant to accept. Since Go 1.25 the standard library ships http.CrossOriginProtection, which rejects non-safe cross-origin browser requests using the Sec-Fetch-Site and Origin headers instead of a per-form secret. This lesson shows what that check decides, where SameSite fits and what stays your responsibility.","nuance":"Only same-origin and none pass the Sec-Fetch-Site check; same-site and cross-site are rejected unless a trusted origin or a bypass pattern applies.","objective":"Protect cookie-authenticated endpoints with net/http's CrossOriginProtection, know what SameSite cookies add and recognize when a synchronizer token is still required.","question":"CrossOriginProtection receives a POST from blog.example.com to app.example.com with Sec-Fetch-Site: same-site. What happens?","references":["https://pkg.go.dev/net/http#CrossOriginProtection","https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Sec-Fetch-Site","https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html"],"reviewAnswer":"Rejected: a sibling subdomain is another origin","reviewPrompt":"Sec-Fetch-Site: same-site POST?","sections":[{"body":"A forged request is genuine HTTP from the victim's own browser, with the victim's cookie and network address, so authentication succeeds. What differs is the initiator: a document from another origin started it. Modern browsers say so. Sec-Fetch-Site carries same-origin, same-site, cross-site or none (the user typed the URL or opened a bookmark), and the Origin header names the initiating origin on POST and CORS requests. Page scripts cannot set either header. A server that refuses state-changing requests initiated by another origin removes the attack without storing anything per session. Credentials that are not ambient, such as a bearer token the client adds to an Authorization header, are never attached by the browser on its own, so they are not exposed to CSRF in the first place.","title":"The browser attaches the cookie; the server must ask who initiated"},{"body":"The program wraps a ServeMux with http.NewCrossOriginProtection, trusts one partner origin, exempts a single-sign-on endpoint that receives a cross-site form post by design and replaces the default 403 body. Each probe sets the headers a particular client would send. httptest.NewRequest uses example.com as the Host, which is what the Origin fallback compares against.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strings\"\n)\n\nfunc newHandler() http.Handler {\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"POST /transfer\", func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprint(w, \"transfer accepted\")\n\t})\n\tmux.HandleFunc(\"GET /balance\", func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprint(w, \"balance shown\")\n\t})\n\tmux.HandleFunc(\"POST /sso/acs\", func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprint(w, \"assertion checked\")\n\t})\n\n\tcop := http.NewCrossOriginProtection()\n\tif err := cop.AddTrustedOrigin(\"https://checkout.partner.example\"); err != nil {\n\t\tpanic(err)\n\t}\n\t// The identity provider posts a signed form cross-site by design.\n\tcop.AddInsecureBypassPattern(\"POST /sso/acs\")\n\tcop.SetDenyHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\thttp.Error(w, \"cross-origin request rejected\", http.StatusForbidden)\n\t}))\n\treturn cop.Handler(mux)\n}\n\ntype probe struct {\n\tlabel, method, path, fetchSite, origin string\n}\n\nfunc main() {\n\th := newHandler()\n\tprobes := []probe{\n\t\t{\"same-origin form\", \"POST\", \"/transfer\", \"same-origin\", \"https://example.com\"},\n\t\t{\"cross-site form\", \"POST\", \"/transfer\", \"cross-site\", \"https://attacker.example\"},\n\t\t{\"sibling subdomain\", \"POST\", \"/transfer\", \"same-site\", \"https://blog.example.com\"},\n\t\t{\"cross-site GET\", \"GET\", \"/balance\", \"cross-site\", \"\"},\n\t\t{\"old browser, Origin only\", \"POST\", \"/transfer\", \"\", \"https://attacker.example\"},\n\t\t{\"old browser, same host\", \"POST\", \"/transfer\", \"\", \"https://example.com\"},\n\t\t{\"curl, no headers\", \"POST\", \"/transfer\", \"\", \"\"},\n\t\t{\"trusted partner\", \"POST\", \"/transfer\", \"cross-site\", \"https://checkout.partner.example\"},\n\t\t{\"SSO bypass pattern\", \"POST\", \"/sso/acs\", \"cross-site\", \"https://idp.example\"},\n\t}\n\tfor _, p := range probes {\n\t\treq := httptest.NewRequest(p.method, p.path, nil) // Host is example.com\n\t\tif p.fetchSite != \"\" {\n\t\t\treq.Header.Set(\"Sec-Fetch-Site\", p.fetchSite)\n\t\t}\n\t\tif p.origin != \"\" {\n\t\t\treq.Header.Set(\"Origin\", p.origin)\n\t\t}\n\t\trec := httptest.NewRecorder()\n\t\th.ServeHTTP(rec, req)\n\t\tfmt.Printf(\"%-26s %d %s\\n\", p.label, rec.Code, strings.TrimSpace(rec.Body.String()))\n\t}\n}","language":"go","title":"Wrap the mux and probe it with every kind of client","walkthrough":"GET, HEAD and OPTIONS pass unconditionally, which is why the cross-site GET succeeds: handlers behind those methods must never change state. A POST with Sec-Fetch-Site: same-origin passes, and so would none; cross-site and same-site are both rejected, because a sibling subdomain is a different origin even though cookies treat it as the same site. Without Sec-Fetch-Site the check compares the Origin host with the Host header, and a request with neither header is treated as a non-browser client such as curl and passes. AddTrustedOrigin matches the full scheme://host[:port] string exactly. AddInsecureBypassPattern uses ServeMux pattern syntax, and a bypassed handler must authenticate the request another way; here the identity provider's signed assertion does that."},{"body":"SameSite=Lax tells the browser to omit the cookie on cross-site subrequests and cross-site POST navigations while still sending it on top-level GET navigations, so a user following a link arrives logged in. Strict withholds it on those navigations too. Both are worth setting on a session cookie, as the session lesson does, but neither replaces an origin check. Site is not origin: blog.example.com and app.example.com are the same site, so a compromised or user-generated subdomain still gets your cookies attached to its requests. Browsers also disagree about the default when SameSite is omitted, and Lax still sends the cookie on top-level GETs, which leaves any state-changing GET handler exposed. Use SameSite to shrink the attack surface and CrossOriginProtection to make the decision.","title":"SameSite cookies narrow exposure; they do not make the decision"},{"body":"Wrap the outermost handler so a route added next quarter is protected automatically, and keep exemptions to a short, reviewed list. Because a *gin.Engine implements http.Handler, cop.Handler(router) protects every Gin route without Gin-specific middleware. If a reverse proxy rewrites the Host header, the Origin fallback for older browsers compares against the wrong host; preserve Host at the proxy or register the public origin with AddTrustedOrigin. Review CORS separately: it decides which origins may read responses, a different question from which may send writes, and a credentialed CORS policy that reflects any origin leaks GET responses even while writes are blocked.","code":"cop := http.NewCrossOriginProtection()\nif err := cop.AddTrustedOrigin(\"https://admin.example.com\"); err != nil {\n\tlog.Fatal(err)\n}\n// A *gin.Engine is an http.Handler, so one wrapper covers every route.\nsrv := &http.Server{\n\tAddr:              \":8080\",\n\tHandler:           cop.Handler(router),\n\tReadHeaderTimeout: 5 * time.Second,\n}","language":"go","title":"Put the check outside everything else","walkthrough":"This fragment runs in your own environment. AddTrustedOrigin returns an error for a value with a path, query or fragment, or without a scheme or host, so check it at startup. Call SetDenyHandler if clients expect a JSON error body; otherwise rejections get a plain-text 403. For a decision inside one handler, Check(r) returns the same error without writing a response."},{"body":"Header-based protection depends on the browser. CrossOriginProtection allows requests that carry neither Sec-Fetch-Site nor Origin, which covers API clients but also very old browsers that send neither on a form post. For a browser that sends Origin but not Sec-Fetch-Site it compares hosts only, so an http:// page on your own host looks like the https:// one; HSTS closes that gap. If policy requires protection for such clients, or if a state change must stay reachable through GET, add a synchronizer token: a random value bound to the session, embedded in each form and compared on submission. Tokens, usually together with re-authentication, also suit especially sensitive actions such as changing an account's email address. No CSRF defense survives XSS on your own origin, because injected script runs same-origin; that is the job of escaping and CSP.","title":"When a synchronizer token is still needed"},{"body":"Test the protection as a table, as the program does: each kind of client, each method, trusted and untrusted origins, and every bypass pattern, asserting both the status and that the handler had no side effect. Review every GET handler for writes, because safe methods always pass. In an end-to-end browser test, submit a form from a second origin and expect a 403. Log rejections with method, path and Origin, so a legitimate integration broken by the check is visible within minutes instead of being reported as a vague 403 days later.","title":"Test the decision table"}],"takeaway":"Wrap the whole handler in http.CrossOriginProtection, keep GET handlers free of side effects, set SameSite on session cookies as a second layer and add synchronizer tokens only where policy requires old-browser coverage.","title":"CSRF: reject cross-origin writes with Sec-Fetch-Site and http.CrossOriginProtection","unitID":"security-web","wrongAnswers":["Allowed, because SameSite cookies treat it as the same site","Allowed whenever an Origin header is also present"]},{"conceptTag":"security.session-cookies","designGuide":{"cautions":["Max-Age and Expires are instructions to the browser, not enforcement.","An in-memory store is per-process and loses every session on restart."],"cost":"A shared session store with TTLs and a user-to-session index, plus one lookup on every authenticated request.","family":"security","flow":["Issue random ID","Rotate at login","Enforce idle + absolute","Delete on logout"],"ratings":[],"strengths":["The prefix and attributes are enforced by the browser on every request.","Server-side expiry and deletion work even when a cookie was copied."]},"hint":"Think about who else might already know the ID that existed before login.","id":"security.session-cookies","introduction":"A session cookie is a bearer credential: whoever presents it is the user until the server decides otherwise. Its attributes control where the browser sends it and whether page scripts can read it; the server-side record controls how long it is honored. Getting either half wrong produces familiar incidents: a cookie copied out by an injected script, a session an attacker fixed before the victim logged in, or a logout that only deleted the browser's copy.","nuance":"Session fixation relies on the identifier surviving authentication. Rotating it, and deleting the old record, makes any copy obtained before login worthless.","objective":"Issue a __Host- session cookie with the right attributes, rotate the ID at login and enforce idle, absolute and logout expiry in a server-side store.","question":"Why must a login handler issue a new session ID instead of attaching the user to the current one?","references":["https://pkg.go.dev/net/http#Cookie","https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie","https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html","https://pkg.go.dev/crypto/rand#Text"],"reviewAnswer":"A pre-login ID an attacker planted becomes useless","reviewPrompt":"Why issue a new ID at login?","sections":[{"body":"HttpOnly hides the cookie from document.cookie, so an XSS payload cannot copy it out, although it can still send requests while the page is open. Secure stops the browser from sending it over plain HTTP. SameSite=Lax keeps it off cross-site subrequests and form posts, which narrows CSRF exposure. Path=/ with no Domain attribute makes a host-only cookie that is not sent to sibling subdomains. The __Host- name prefix turns those properties into browser-enforced rules: a cookie named __Host-session is rejected unless it is Secure, set from a secure origin, has Path=/ and carries no Domain, so a compromised subdomain cannot plant or overwrite it. Go's net/http does not check prefix rules; the browser does.","title":"What each attribute buys"},{"body":"The program models a session store with an injected clock, so expiry is deterministic. The cookie carries only a random ID from crypto/rand.Text; the user, the creation time and the last activity live on the server. It walks through a login that follows a planted pre-login ID, idle expiry, absolute expiry of a busy session and logout, and prints the Set-Cookie headers with the random value masked.","code":"package main\n\nimport (\n\t\"crypto/rand\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst cookieName = \"__Host-session\"\n\nvar (\n\terrNoSession   = errors.New(\"session not found\")\n\terrIdleExpired = errors.New(\"session expired (idle)\")\n\terrAbsExpired  = errors.New(\"session expired (absolute)\")\n)\n\ntype session struct {\n\tuserID   string\n\tcreated  time.Time\n\tlastSeen time.Time\n}\n\n// store owns every session; the cookie only carries an unguessable key.\ntype store struct {\n\tmu       sync.Mutex\n\tbyID     map[string]*session\n\tnow      func() time.Time\n\tidle     time.Duration\n\tabsolute time.Duration\n}\n\nfunc (s *store) create(userID string) string {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tid := rand.Text() // at least 128 bits from crypto/rand\n\tt := s.now()\n\ts.byID[id] = &session{userID: userID, created: t, lastSeen: t}\n\treturn id\n}\n\nfunc (s *store) lookup(id string) (string, error) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tsess, ok := s.byID[id]\n\tif !ok {\n\t\treturn \"\", errNoSession\n\t}\n\tt := s.now()\n\tswitch {\n\tcase t.Sub(sess.created) > s.absolute:\n\t\tdelete(s.byID, id)\n\t\treturn \"\", errAbsExpired\n\tcase t.Sub(sess.lastSeen) > s.idle:\n\t\tdelete(s.byID, id)\n\t\treturn \"\", errIdleExpired\n\t}\n\tsess.lastSeen = t\n\treturn sess.userID, nil\n}\n\n// login discards the pre-login session and issues a fresh ID.\nfunc (s *store) login(oldID, userID string) string {\n\ts.destroy(oldID)\n\treturn s.create(userID)\n}\n\nfunc (s *store) destroy(id string) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tdelete(s.byID, id)\n}\n\nfunc sessionCookie(id string, maxAge int) *http.Cookie {\n\treturn &http.Cookie{\n\t\tName:     cookieName,\n\t\tValue:    id,\n\t\tPath:     \"/\",\n\t\tMaxAge:   maxAge,\n\t\tHttpOnly: true,\n\t\tSecure:   true,\n\t\tSameSite: http.SameSiteLaxMode,\n\t}\n}\n\nfunc setCookieHeader(c *http.Cookie) string {\n\trec := httptest.NewRecorder()\n\thttp.SetCookie(rec, c)\n\th := rec.Header().Get(\"Set-Cookie\")\n\tif c.Value != \"\" {\n\t\th = strings.Replace(h, c.Value, \"<id>\", 1)\n\t}\n\treturn h\n}\n\nfunc show(label string, st *store, id string) {\n\tuser, err := st.lookup(id)\n\tif err != nil {\n\t\tfmt.Printf(\"%s: %v\\n\", label, err)\n\t\treturn\n\t}\n\tfmt.Printf(\"%s: ok %s\\n\", label, user)\n}\n\nfunc main() {\n\tclock := time.Date(2026, 1, 5, 9, 0, 0, 0, time.UTC)\n\tst := &store{\n\t\tbyID:     map[string]*session{},\n\t\tnow:      func() time.Time { return clock },\n\t\tidle:     30 * time.Minute,\n\t\tabsolute: 8 * time.Hour,\n\t}\n\n\t// An attacker can plant a pre-login ID in the victim's browser.\n\tplanted := st.create(\"\")\n\tid := st.login(planted, \"user-42\")\n\tfmt.Println(setCookieHeader(sessionCookie(id, int(st.absolute.Seconds()))))\n\tshow(\"planted pre-login ID\", st, planted)\n\tfmt.Printf(\"new ID differs: %t, length %d\\n\", id != planted, len(id))\n\n\tclock = clock.Add(20 * time.Minute)\n\tshow(\"after 20m\", st, id)\n\tclock = clock.Add(31 * time.Minute)\n\tshow(\"after 31m without a request\", st, id)\n\n\tid = st.login(\"\", \"user-42\")\n\tfor range 19 { // a request every 25 minutes keeps the idle timer fresh\n\t\tclock = clock.Add(25 * time.Minute)\n\t\tif _, err := st.lookup(id); err != nil {\n\t\t\tfmt.Println(\"unexpected:\", err)\n\t\t}\n\t}\n\tshow(\"busy session at 7h55m\", st, id)\n\tclock = clock.Add(25 * time.Minute)\n\tshow(\"busy session at 8h20m\", st, id)\n\n\tid = st.login(\"\", \"user-42\")\n\tst.destroy(id) // logout invalidates the record on the server\n\tshow(\"replayed cookie after logout\", st, id)\n\tfmt.Println(setCookieHeader(sessionCookie(\"\", -1)))\n}","language":"go","title":"A store that owns expiry and rotation","walkthrough":"http.SetCookie renders the attributes in a fixed order; Max-Age=28800 matches the eight-hour absolute limit, but the server never relies on the browser forgetting the cookie. login destroys the old record before creating a new one, so the planted ID is dead and the user gets a fresh 26-character base32 ID; rand.Text guarantees at least 128 bits of randomness and may return longer strings in future releases. lookup checks the absolute limit against created and the idle limit against lastSeen, deletes expired records and refreshes lastSeen only on success. The busy session survives nineteen requests 25 minutes apart and still ends after eight hours. destroy removes the record, so a copied cookie replayed after logout finds nothing, and the final header, empty with Max-Age=0, asks the browser to drop its copy."},{"body":"Session fixation works when an application keeps the identifier it issued before login. An attacker obtains a valid anonymous ID, gets it into the victim's browser through a crafted link, a sibling subdomain or an injected header, and waits; once the victim authenticates, the attacker's copy of the same ID is logged in too. Issuing a new ID at login, and again whenever privileges rise, for example after step-up authentication or entering an admin mode, makes every earlier copy worthless. Carry over only the pre-login data you choose, such as a cart, by copying it into the new record. The __Host- prefix makes planting harder; rotation makes it pointless. Use both.","title":"Rotate the ID on every privilege change"},{"body":"Gin's positional c.SetCookie(name, value, maxAge, path, domain, secure, httpOnly) takes SameSite from a separate c.SetSameSite call and URL-escapes the value, which makes a missing attribute easy to overlook; c.SetCookieData accepts a complete http.Cookie. Leave Domain empty: setting it to example.com widens the cookie to every subdomain and is forbidden with the __Host- prefix. Over plain HTTP on a development hostname the browser drops a Secure cookie, so run development over HTTPS rather than adding a flag that disables Secure and can leak into a release.","code":"// net/http\nhttp.SetCookie(w, &http.Cookie{\n\tName: \"__Host-session\", Value: id, Path: \"/\",\n\tMaxAge: 8 * 60 * 60, HttpOnly: true, Secure: true,\n\tSameSite: http.SameSiteLaxMode,\n})\n\n// Gin: SetCookieData takes the whole cookie, including SameSite.\nc.SetCookieData(&http.Cookie{\n\tName: \"__Host-session\", Value: id, Path: \"/\",\n\tMaxAge: 8 * 60 * 60, HttpOnly: true, Secure: true,\n\tSameSite: http.SameSiteLaxMode,\n})","language":"go","title":"Set and clear the cookie in net/http and Gin","walkthrough":"This fragment runs inside your own handler. MaxAge is in seconds, and a negative value emits Max-Age=0, which deletes the cookie. Both calls produce the same header, so a test can assert on the Set-Cookie string exactly as the program does. Gin's SetCookieData fills in Path and SameSite only when they are empty, so the explicit values above are what is sent."},{"body":"An idle timeout limits how long an abandoned, unlocked laptop stays logged in; an absolute timeout limits how long a stolen cookie is useful even if the thief keeps it busy. Choose both from the application's risk, for example 30 minutes idle and 8 hours absolute for an admin console, and enforce them where the record lives, not through Max-Age or Expires, which only instruct an honest browser. Logout must delete the server record and then clear the cookie; clearing only the cookie leaves every copied value valid. Plan the other invalidations too: a password change or account lock should end all of the user's sessions, which needs an index from user to session IDs. A real store is Redis or a database table with TTLs and that index; the in-memory map here is a model that loses everything on restart and is not shared between replicas.","title":"Expiry and logout belong to the server"},{"body":"Read the Set-Cookie header in a test rather than the struct you meant to send, and assert HttpOnly, Secure, SameSite, Path=/ and the __Host- name. Assert that the ID changes across login and that the old ID fails afterwards. Advance a fake clock past the idle and the absolute limits and expect rejection, and replay a cookie after logout. Keep session IDs out of logs, URLs and analytics events. If a leaked session table would be serious, store a hash of each ID instead of the ID itself, a token-design decision covered elsewhere in this course.","title":"Review checklist"}],"takeaway":"Name the cookie __Host-, set HttpOnly, Secure, SameSite and Path=/, issue a fresh crypto/rand ID at every login and enforce idle, absolute and logout expiry in the server-side store.","title":"Session cookies: lock down the attributes and keep the session's lifetime on the server","unitID":"security-web","wrongAnswers":["HttpOnly cookies cannot be updated after they are set","A new ID stops injected scripts from reading the cookie"]},{"conceptTag":"security.path-traversal","designGuide":{"cautions":["Root does not stop mount points, device files or hard links inside the tree.","archive/zip accepts non-local entry names unless zipinsecurepath=0 is set."],"cost":"Passing a *os.Root instead of a base-path string and a few checks per archive entry; component-wise resolution adds a little work to each open.","family":"security","flow":["Reject non-local names","Open os.Root once","Operate through Root","Refuse links in archives"],"ratings":[],"strengths":["Neither .. nor symlinks can lead outside the opened directory.","Errors carry only the relative name, so they are safe to log."]},"hint":"Ask what Clean and Join know about the files that actually exist.","id":"security.path-traversal","introduction":"Path traversal turns a file name from a request into access somewhere else on disk: ../ segments, an absolute path or a symlink that leads out of the intended directory. The classic Go defense, filepath.Join plus Clean plus a prefix check, works on strings while the kernel resolves the real path later, symlinks included. Go 1.24 added os.Root, which opens a directory once and resolves every later name inside it, and Go 1.25 extended it with ReadFile, WriteFile, MkdirAll and other helpers.","nuance":"Both functions are purely lexical. A symlink inside the directory can point anywhere, so only resolution relative to an open directory, as os.Root does, is a boundary.","objective":"Open user-named files through os.Root, use filepath.IsLocal and Localize for early rejection and extract archives without zip-slip.","question":"A handler joins a cleaned file name to its upload directory before opening it. Why can the opened file still be outside that directory?","references":["https://pkg.go.dev/os#Root","https://go.dev/blog/osroot","https://pkg.go.dev/path/filepath#IsLocal","https://owasp.org/www-community/attacks/Path_Traversal"],"reviewAnswer":"It edits strings; symlinks resolve later on disk","reviewPrompt":"Why isn't Join+Clean a boundary?","sections":[{"body":"filepath.Clean removes . and .. elements and duplicate separators, and filepath.Join cleans its result. Neither consults the disk. If the base directory contains a symbolic link, whether uploaded by a user, unpacked from an archive or left by a deploy, a clean, local-looking name such as latest.txt can resolve to a file outside the base. Prefix checks add their own bug: strings.HasPrefix(p, \"/srv/public\") also accepts /srv/public-backup. And code that resolves symlinks first and opens second can be raced by a concurrent rename. The robust design resolves the name relative to an already-open directory, one component at a time, and refuses any step that leaves it.","title":"Lexical checks cannot see the filesystem"},{"body":"The program builds a small tree under os.TempDir(): a public directory with readme.txt, a secret.txt beside it and a relative symlink inside public that points at the secret. It asks for four names in three ways: the lexical filepath.IsLocal test, a naive Join of the cleaned name, and Root.ReadFile on a root opened at public. The deferred RemoveAll deletes the whole tree afterwards.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\n// naiveRead looks careful but only manipulates strings.\nfunc naiveRead(base, name string) string {\n\tdata, err := os.ReadFile(filepath.Join(base, filepath.Clean(name)))\n\tif err != nil {\n\t\treturn \"error\"\n\t}\n\treturn string(data)\n}\n\n// rootRead resolves every component inside the opened directory.\nfunc rootRead(root *os.Root, name string) string {\n\tdata, err := root.ReadFile(name)\n\tif err != nil {\n\t\treturn \"denied: \" + err.Error()\n\t}\n\treturn string(data)\n}\n\nfunc main() {\n\tdir, err := os.MkdirTemp(\"\", \"traversal-demo-*\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer os.RemoveAll(dir)\n\n\tpublic := filepath.Join(dir, \"public\")\n\tmust(os.Mkdir(public, 0o755))\n\tmust(os.WriteFile(filepath.Join(public, \"readme.txt\"), []byte(\"public notes\"), 0o644))\n\tmust(os.WriteFile(filepath.Join(dir, \"secret.txt\"), []byte(\"SECRET\"), 0o600))\n\t// A relative symlink that a user upload or a bad deploy could leave behind.\n\tmust(os.Symlink(\"../secret.txt\", filepath.Join(public, \"latest.txt\")))\n\n\troot, err := os.OpenRoot(public)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer root.Close()\n\n\tfor _, name := range []string{\"readme.txt\", \"../secret.txt\", \"/readme.txt\", \"latest.txt\"} {\n\t\tfmt.Printf(\"%-15q IsLocal=%-5t join=%-12s root=%s\\n\",\n\t\t\tname, filepath.IsLocal(name), naiveRead(public, name), rootRead(root, name))\n\t}\n}\n\nfunc must(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}","language":"go","title":"Compare a string join with os.Root","walkthrough":"IsLocal rejects ../secret.txt and /readme.txt, but reports latest.txt as local because it never looks at the disk. The naive join leaks the secret twice: once through .., and once through the symlink that no lexical check can see. Join treats /readme.txt as relative, so that request happens to stay inside, which is luck rather than policy. os.Root refuses all three escapes with the same error, path escapes from parent. The error's path is the name you passed, never the root's location, so it is safe to log. Root follows symlinks only while they stay inside the root and rejects absolute link targets outright."},{"body":"Rejecting obviously bad names before touching the disk gives clear 400 responses and readable logs. filepath.IsLocal reports whether a path is non-empty, not absolute and still inside its base after lexical cleaning; on Windows it also rejects reserved names such as NUL. When names arrive slash-separated, as in URLs, io/fs paths and archives, filepath.Localize converts them to the OS form and fails for anything that is not a valid io/fs path, so its result is always local. Neither function sees symlinks, so pair them with os.Root. To serve a directory over HTTP, http.FileServerFS(root.FS()) keeps the confinement, whereas http.Dir and os.DirFS document that they follow symlinks wherever they point.","title":"IsLocal and Localize are early filters, not boundaries"},{"body":"Zip-slip is path traversal delivered in bulk: an entry named ../../escape.txt or /etc/cron.d/job is written wherever it points if extraction code joins entry names to a destination. archive/zip still accepts such names by default in Go 1.27; only with GODEBUG=zipinsecurepath=0 does NewReader return ErrInsecurePath, alongside a usable reader. The extractor below validates each name with Localize, refuses symlinks and other non-regular entries, writes through os.Root with O_EXCL so it never follows or overwrites an existing file, and caps each file's size.","code":"package main\n\nimport (\n\t\"archive/zip\"\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/fs\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\nconst maxFileBytes = 1 << 20\n\n// extract writes regular files from zr beneath root and refuses everything else.\nfunc extract(root *os.Root, zr *zip.Reader) error {\n\tfor _, f := range zr.File {\n\t\tif f.FileInfo().IsDir() {\n\t\t\tcontinue // directories are created on demand below\n\t\t}\n\t\t// Zip names are slash-separated; Localize rejects absolute names,\n\t\t// \"..\" elements and names the OS cannot represent.\n\t\tname, err := filepath.Localize(f.Name)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"skip %q: not a local path\\n\", f.Name)\n\t\t\tcontinue\n\t\t}\n\t\tif !f.Mode().IsRegular() {\n\t\t\tfmt.Printf(\"skip %q: not a regular file\\n\", f.Name)\n\t\t\tcontinue\n\t\t}\n\t\tif err := root.MkdirAll(filepath.Dir(name), 0o755); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := copyFile(root, name, f); err != nil {\n\t\t\treturn fmt.Errorf(\"%s: %w\", f.Name, err)\n\t\t}\n\t\tfmt.Printf(\"wrote %q\\n\", name)\n\t}\n\treturn nil\n}\n\nfunc copyFile(root *os.Root, name string, f *zip.File) error {\n\tsrc, err := f.Open()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer src.Close()\n\tdst, err := root.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)\n\tif err != nil {\n\t\treturn err\n\t}\n\tn, err := io.Copy(dst, io.LimitReader(src, maxFileBytes+1))\n\tif cerr := dst.Close(); err == nil {\n\t\terr = cerr\n\t}\n\tif err == nil && n > maxFileBytes {\n\t\terr = errors.New(\"file exceeds size limit\")\n\t}\n\treturn err\n}\n\nfunc hostileArchive() *bytes.Reader {\n\tvar buf bytes.Buffer\n\tzw := zip.NewWriter(&buf)\n\tadd := func(name string, mode fs.FileMode, body string) {\n\t\th := &zip.FileHeader{Name: name, Method: zip.Deflate}\n\t\th.SetMode(mode)\n\t\tw, err := zw.CreateHeader(h)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tif _, err := io.WriteString(w, body); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\tadd(\"readme.txt\", 0o644, \"hello\")\n\tadd(\"docs/guide.txt\", 0o644, \"guide\")\n\tadd(\"../../escape.txt\", 0o644, \"zip slip\")\n\tadd(\"/etc/cron.d/job\", 0o644, \"absolute\")\n\tadd(\"docs/link\", fs.ModeSymlink|0o777, \"../../../home\")\n\tif err := zw.Close(); err != nil {\n\t\tpanic(err)\n\t}\n\treturn bytes.NewReader(buf.Bytes())\n}\n\nfunc main() {\n\tdir, err := os.MkdirTemp(\"\", \"unzip-demo-*\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer os.RemoveAll(dir)\n\troot, err := os.OpenRoot(dir)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer root.Close()\n\n\tra := hostileArchive()\n\tzr, err := zip.NewReader(ra, ra.Size())\n\tif err != nil && !errors.Is(err, zip.ErrInsecurePath) {\n\t\tpanic(err)\n\t}\n\tif err := extract(root, zr); err != nil {\n\t\tfmt.Println(\"extract failed:\", err)\n\t}\n}","language":"go","title":"Extract archives without zip-slip","walkthrough":"Directory entries are skipped because Root.MkdirAll creates parents on demand. Localize rejects the two hostile names before any write, and the symlink entry is refused by its mode rather than its name. Writes go through root.OpenFile, so even a name that passed every check cannot follow a link already present in the destination. io.LimitReader allows one byte past the limit so an oversize entry is detected rather than silently truncated. Running the program prints one wrote or skip line per entry and removes its temporary directory. Production extractors also cap the entry count and the total uncompressed size, because a small upload can expand into gigabytes."},{"body":"os.Root guarantees that names resolve beneath the root; it does not make everything beneath the root safe. It does not stop traversal across mount points or bind mounts inside the tree, it does not hide device files or /proc entries reachable within it, and a hard link inside the root to a file elsewhere is simply a file inside the root. On Unix, Root.Chmod, Chown and Chtimes have a documented race with symlink swaps. Prefer designs where users never name paths: store uploads under server-generated IDs, keep the original filename as metadata, and look files up by ID after an authorization check. In tests, keep a table of hostile names, including .., absolute paths, encoded dots if any layer decodes them and a planted symlink, and assert that every one is refused. Run the service as a user that cannot read secrets it does not need.","title":"What os.Root does not promise, and better designs"}],"takeaway":"Reject non-local names early with filepath.IsLocal or Localize, then perform every file operation through os.Root so that .. and symlinks cannot leave the directory.","title":"Path traversal: confine file access with os.Root, because Join and Clean only edit strings","unitID":"security-web","wrongAnswers":["Clean keeps .. segments when the name is absolute","Join returns an error for .. that the handler ignores"]},{"conceptTag":"security.command-injection","designGuide":{"cautions":["-- is honored by each program's parser, not by Go; check the target tool.","A nil Env hands every secret in the service's environment to the child."],"cost":"An allow-list per tool, explicit Env and Dir and a bounded output writer; starting a process stays far more expensive than calling a library.","family":"security","flow":["Fix program and argv","Allow-list operations","End options before data","Bound time and env"],"ratings":[],"strengths":["Without a shell, no metacharacter in a user value is ever parsed.","cmd.Args can be asserted in tests without running anything."]},"hint":"Ask who reads argv once the new process has started.","id":"security.command-injection","introduction":"Go's os/exec does not invoke a shell: exec.Command takes a program and an argument slice, so semicolons and $(...) inside an argument are ordinary bytes. The operations lessons on Bash arguments and safe CLIs already rely on that. This lesson covers the injection that survives without a shell: a user value read as an option by the target program, an operation chosen by the request, and a child process that inherits your environment and outlives its deadline.","nuance":"Each program parses its own arguments, so a value starting with - can become a flag. -- ends option parsing in programs that support it, and validation covers those that do not.","objective":"Start external tools with exec.CommandContext and a fixed argv, block argument injection with validation and --, and bound the child's time and environment.","question":"exec.Command runs no shell. Why put \"--\" before a user-supplied file name in the argument list?","references":["https://pkg.go.dev/os/exec#Cmd","https://go.dev/blog/path-security","https://cheatsheetseries.owasp.org/cheatsheets/OS_Command_Injection_Defense_Cheat_Sheet.html"],"reviewAnswer":"The program parsing that value as an option","reviewPrompt":"What does -- before a value stop?","sections":[{"body":"Shell injection needs a shell: sh -c, bash -c, cmd /c, or a script that hands its arguments to eval. Concatenating a user value into that single command string lets ; | && and $( ) start new commands, and quoting by hand fails on the first input that contains a quote. Argument injection needs no shell at all. Every program parses its own argv, so a value beginning with a dash is read as an option: --files0-from=FILE for GNU wc, --upload-pack=COMMAND for git ls-remote, -o for many tools that write files. The exec call is correct and the user still controls the program's behavior. Defending against both means deciding which argv positions hold data and making the target program agree.","title":"Two injections: shell syntax and argument position"},{"body":"The program constructs commands and prints cmd.Args, the exact argv the child would receive. It never calls Run, Start or Output, so no process starts. It contrasts a shell string with a direct argv, rejects names that begin with a dash, and builds git invocations from an allow-list of operations with a timeout, a controlled environment and a bounded wait.","code":"package main\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os/exec\"\n\t\"strings\"\n\t\"syscall\"\n\t\"time\"\n)\n\n// Vulnerable: the shell parses name as syntax, so ; | $( ) all work.\nfunc countViaShell(name string) *exec.Cmd {\n\treturn exec.Command(\"sh\", \"-c\", \"wc -l \"+name)\n}\n\n// countLines passes name as one argv element and ends option parsing first.\nfunc countLines(ctx context.Context, name string) (*exec.Cmd, error) {\n\tif name == \"\" || strings.HasPrefix(name, \"-\") {\n\t\treturn nil, errors.New(\"file name must not be empty or start with '-'\")\n\t}\n\treturn exec.CommandContext(ctx, \"wc\", \"-l\", \"--\", name), nil\n}\n\n// gitOps is the whole surface a request can reach: fixed argv per operation.\nvar gitOps = map[string][]string{\n\t\"status\": {\"status\", \"--porcelain=v1\"},\n\t\"log\":    {\"log\", \"--oneline\", \"--max-count=20\"},\n}\n\nfunc gitCommand(ctx context.Context, op string) (*exec.Cmd, error) {\n\targs, ok := gitOps[op]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"operation %q is not allowed\", op)\n\t}\n\tcmd := exec.CommandContext(ctx, \"git\", args...)\n\tcmd.Dir = \"/srv/repos/site\"\n\tcmd.Env = []string{\"PATH=/usr/bin:/bin\", \"LANG=C\", \"GIT_TERMINAL_PROMPT=0\"}\n\tcmd.Cancel = func() error { return cmd.Process.Signal(syscall.SIGTERM) }\n\tcmd.WaitDelay = 2 * time.Second\n\treturn cmd, nil\n}\n\nfunc main() {\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\n\thostile := \"report.txt; touch pwned\"\n\tfmt.Printf(\"shell argv: %q\\n\", countViaShell(hostile).Args)\n\n\tfor _, name := range []string{hostile, \"--files0-from=/etc/passwd\", \"-\"} {\n\t\tcmd, err := countLines(ctx, name)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"rejected %q: %v\\n\", name, err)\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Printf(\"direct argv: %q\\n\", cmd.Args)\n\t}\n\n\tfor _, op := range []string{\"log\", \"push\"} {\n\t\tcmd, err := gitCommand(ctx, op)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"rejected:\", err)\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Printf(\"git argv: %q\\n\", cmd.Args)\n\t\tfmt.Printf(\"git env:  %q\\n\", cmd.Env)\n\t\tfmt.Println(\"git wait delay:\", cmd.WaitDelay)\n\t}\n\t// Nothing above calls Run, Start or Output: no process was started.\n}","language":"go","title":"Build the argv and print it without running anything","walkthrough":"In the shell form the hostile name is part of one script, so sh would run touch pwned after wc. In the direct form the same bytes are one argument after --, and wc would only report that no file has that odd name. countLines rejects a leading dash before -- even matters; that also catches a lone -, which conventionally means standard input and which -- does not neutralize. gitCommand never copies request text into argv: the request selects a key, the argv comes from the map, and push is refused. Env replaces the environment entirely rather than adding to it. Cancel sends SIGTERM instead of the default Kill when the context ends (Windows supports only Kill), and WaitDelay bounds how long Wait then waits for the process to exit and its pipes to close. Args[0] is the name as written; the resolved executable is in cmd.Path."},{"body":"-- is a convention of each program's option parser, not of the kernel or of Go. Most getopt-style tools honor it, some treat it as data, and git uses it to separate revisions from paths, so git log -- main means the path main; git 2.24 and later accept --end-of-options for the revision case. Read the target's documentation, place user values after the terminator it actually supports, and still reject values that start with a dash when the field never legitimately does. Where the tool can read data from standard input or a file, prefer that over argv for free-form text. Never let a request choose the program name, and avoid wrapping tools whose purpose is to run other commands, such as find -exec, xargs, env, ssh or a script that calls eval.","title":"Make the target program agree where options end"},{"body":"Map each user-visible operation to a complete argv in code, as gitOps does, and validate the few free-form values against strict patterns: a commit hash as 40 hexadecimal characters, a branch name against the repository's real branch list. Since Go 1.19, exec.LookPath refuses a program found through a relative PATH entry such as . and returns exec.ErrDot, which closes a classic hijack; an absolute path from configuration is clearer still. On Windows, a command line is a single string that each program parses itself, and .bat or .cmd files are interpreted by cmd.exe with its own metacharacters, so do not pass untrusted arguments to batch files there.","title":"Choose the executable and the operation in code"},{"body":"A request-scoped context lets a client disconnect or a deadline stop the child. By default CommandContext kills the process when the context is done, but a grandchild holding the output pipes can still keep Wait blocked, which is what WaitDelay bounds. Set Env explicitly: a nil Env inherits every variable of your service, including database URLs and API tokens, which the child may log or forward. Set Dir rather than relying on the service's working directory, cap captured output, and return a generic error to the client while logging argv and exit status for operators.","code":"ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)\ndefer cancel()\ncmd, err := gitCommand(ctx, r.PathValue(\"op\"))\nif err != nil {\n\thttp.Error(w, \"unknown operation\", http.StatusBadRequest)\n\treturn\n}\nout := newLimitedBuffer(1 << 20) // an io.Writer that fails past 1 MiB\ncmd.Stdout, cmd.Stderr = out, out\nif err := cmd.Run(); err != nil {\n\tif ctx.Err() != nil {\n\t\thttp.Error(w, \"operation timed out\", http.StatusGatewayTimeout)\n\t\treturn\n\t}\n\tlog.Printf(\"git %q failed: %v\", cmd.Args, err)\n\thttp.Error(w, \"operation failed\", http.StatusInternalServerError)\n\treturn\n}","language":"go","title":"Bound time, output and inherited state","walkthrough":"This fragment runs in your own service and reuses gitCommand from the program. newLimitedBuffer stands for a small io.Writer you write that returns an error once its byte budget is spent; an unbounded bytes.Buffer lets a chatty tool exhaust memory. Checking ctx.Err() separates a timeout from a non-zero exit, so the client sees 504 for one and 500 for the other, and neither response includes the tool's stderr."},{"body":"Until Start is called, an exec.Cmd is a plain struct, so unit tests can assert on cmd.Args, cmd.Env and cmd.Dir for every operation and every hostile input, exactly as the program prints them, without installing the tool. Add a few integration tests that really run the command against a fixture directory with a short timeout. In review, search for sh -c, bash -c and cmd /c, for exec.Command calls whose program is not a constant, and for request-handling code that leaves Env nil.","title":"Test the argv, not the side effect"}],"takeaway":"Pass a fixed program and argv to exec.CommandContext, take operations from an allow-list, keep user values out of option position with validation and the target's terminator, and set Env, Dir, Cancel and WaitDelay deliberately.","title":"Command injection: run tools without a shell and keep user input out of option position","unitID":"security-web","wrongAnswers":["It stops the shell from expanding ; and | characters","It makes os/exec quote the argument for the kernel"]},{"conceptTag":"security.open-redirects","designGuide":{"cautions":["net/url and browsers disagree on backslashes, tabs and userinfo.","http.Redirect cleans relative paths but passes //host targets through."],"cost":"A small validator and a host allow-list; keeping return paths server-side costs one session field.","family":"security","flow":["Reject backslash, controls","Parse the target","Path or allow-listed host","Fall back to fixed page"],"ratings":[],"strengths":["Only two target shapes exist, so the policy fits in a short table.","Rejected input is never echoed into the Location header."]},"hint":"Compare how a browser resolves two leading slashes with how a file path would.","id":"security.open-redirects","introduction":"Login, logout and OAuth flows often carry a next or return_to parameter. If the server redirects to whatever it contains, an attacker can send a link that starts on your trusted domain and ends on a lookalike login page, and in OAuth flows a redirect can leak codes or tokens. The obvious fix, allow only relative paths, is harder than it looks: browsers parse URLs by the WHATWG URL Standard, Go's net/url follows RFC 3986, and every difference between them is a bypass.","nuance":"Two leading slashes begin a scheme-relative URL: the browser keeps the current scheme and switches to the host after the slashes. Require exactly one leading slash.","objective":"Validate redirect targets so only same-site paths and allow-listed https URLs pass, including the //host, backslash and userinfo tricks that browsers and net/url read differently.","question":"A login handler redirects to next only if it starts with \"/\". Why is next=//evil.example still dangerous?","references":["https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html","https://pkg.go.dev/net/url#Parse","https://pkg.go.dev/net/http#Redirect","https://www.rfc-editor.org/rfc/rfc9700"],"reviewAnswer":"No: browsers read // as the start of a new host","reviewPrompt":"Is //evil.example a local path?","sections":[{"body":"A target of //evil.example/login starts with a slash, yet browsers read it as a scheme-relative URL that changes the host. Browsers also treat a backslash like a forward slash in http and https URLs, so /\\evil.example becomes //evil.example on its way to the address bar, and they delete tab and newline characters anywhere in a URL, so a slash, a tab and another slash collapse into the same thing. Absolute URLs bring their own tricks: in https://docs.example.com@evil.example the first part is userinfo and the host is evil.example, and https://docs.example.com.evil.example/ passes any check that only compares a prefix. None of these needs a bug in your router, only validation that inspects a string instead of the destination a browser will compute.","title":"Why starting with / is not the same as staying on this site"},{"body":"redirectTarget accepts exactly two shapes: a relative reference that begins with a single slash, or an https URL whose host is on an explicit allow-list. Everything else is rejected with a reason. The table compares it with a common first attempt that allows anything beginning with / or with the docs prefix, and the last two lines run the validator inside a login handler through httptest.","code":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"net/url\"\n\t\"strings\"\n)\n\n// allowedHosts lists the only absolute destinations; compare exact hostnames.\nvar allowedHosts = map[string]bool{\"docs.example.com\": true}\n\nfunc redirectTarget(raw string) (string, error) {\n\tif raw == \"\" {\n\t\treturn \"\", errors.New(\"empty\")\n\t}\n\t// Browsers treat \\ like / and strip tabs and newlines; Go's parser does not.\n\tif strings.ContainsFunc(raw, func(r rune) bool { return r == '\\\\' || r < 0x20 || r == 0x7f }) {\n\t\treturn \"\", errors.New(\"backslash or control character\")\n\t}\n\tu, err := url.Parse(raw)\n\tif err != nil {\n\t\treturn \"\", errors.New(\"unparseable\")\n\t}\n\tif u.Scheme == \"\" && u.Host == \"\" && u.User == nil {\n\t\tif !strings.HasPrefix(raw, \"/\") || strings.HasPrefix(raw, \"//\") {\n\t\t\treturn \"\", errors.New(\"relative target must start with exactly one /\")\n\t\t}\n\t\treturn u.String(), nil\n\t}\n\t// u.Host includes any port, so \"docs.example.com:8443\" is not allowed either.\n\tif !allowedHosts[u.Host] {\n\t\treturn \"\", fmt.Errorf(\"host %q not allowed\", u.Host)\n\t}\n\tif u.Scheme != \"https\" || u.User != nil {\n\t\treturn \"\", errors.New(\"only https URLs without userinfo\")\n\t}\n\treturn u.String(), nil\n}\n\n// naiveTarget is a common first attempt: a local path or \"our\" docs prefix.\nfunc naiveTarget(raw string) bool {\n\treturn strings.HasPrefix(raw, \"/\") || strings.HasPrefix(raw, \"https://docs.example.com\")\n}\n\nfunc main() {\n\tinputs := []string{\n\t\t\"/settings?tab=keys\",\n\t\t\"https://docs.example.com/guide\",\n\t\t\"http://docs.example.com/guide\",\n\t\t\"//evil.example/login\",\n\t\t`/\\evil.example`,\n\t\t\"/\\t/evil.example\",\n\t\t\"https://docs.example.com@evil.example/\",\n\t\t\"https://docs.example.com.evil.example/\",\n\t\t\"https:evil.example\",\n\t\t\"javascript:alert(1)\",\n\t\t\"settings\",\n\t}\n\tfor _, in := range inputs {\n\t\tnaive := \"reject\"\n\t\tif naiveTarget(in) {\n\t\t\tnaive = \"allow\"\n\t\t}\n\t\tif target, err := redirectTarget(in); err != nil {\n\t\t\tfmt.Printf(\"%-42q naive=%-6s safe=reject (%v)\\n\", in, naive, err)\n\t\t} else {\n\t\t\tfmt.Printf(\"%-42q naive=%-6s safe=allow %s\\n\", in, naive, target)\n\t\t}\n\t}\n\n\t// The handler falls back to a fixed page instead of echoing bad input.\n\th := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\ttarget, err := redirectTarget(r.URL.Query().Get(\"next\"))\n\t\tif err != nil {\n\t\t\ttarget = \"/\"\n\t\t}\n\t\thttp.Redirect(w, r, target, http.StatusSeeOther)\n\t})\n\tfor _, next := range []string{\"/settings\", \"//evil.example\"} {\n\t\trec := httptest.NewRecorder()\n\t\th.ServeHTTP(rec, httptest.NewRequest(\"POST\", \"/login?next=\"+url.QueryEscape(next), nil))\n\t\tfmt.Printf(\"POST /login next=%s -> %d Location: %s\\n\", next, rec.Code, rec.Header().Get(\"Location\"))\n\t}\n}","language":"go","title":"A decision table for redirect targets","walkthrough":"Backslashes and control characters are rejected before parsing, because net/url either keeps them as path bytes or refuses them while a browser silently rewrites them. url.Parse then decides the shape: no scheme, no host and no userinfo means a relative reference, which must start with one slash and not two. For absolute URLs, u.Host, which includes any port, must equal an allow-list entry, so the userinfo and suffix tricks reveal their real hosts. https:evil.example parses with an empty host and an opaque part, and javascript: URLs have no host either, so both fail. The handler never echoes a rejected value: it falls back to / and answers 303 See Other so the browser follows with GET after the login POST."},{"body":"url.Parse is a parser, not a validator. It accepts almost any string: settings parses as a relative path, javascript:alert(1) as a scheme with an opaque part, and a leading space simply becomes part of the path. It lowercases the scheme but not the host, so normalize the host with strings.ToLower if DOCS.example.com should match. Never allow-list by string suffix, because badexample.com ends with example.com; if subdomains are allowed, require the host to equal example.com or end with .example.com. http.Redirect, and Gin's c.Redirect, which calls it, turn a relative target into an absolute path and clean it, but they pass //evil.example and /\\evil.example through unchanged, so they are not validators either. Validate first and redirect to the value you validated.","title":"What url.Parse does and does not tell you"},{"body":"The safest redirect parameter is not a URL. Store the intended destination server-side, for example in the session before sending the user to log in, and carry nothing or an opaque key in the query string. When a client must name a destination, let it choose from names that map to URLs in configuration. OAuth makes this mandatory for redirect_uri: the OAuth 2.0 security best current practice requires authorization servers to compare it with pre-registered values by exact string match, and your own post-login return path deserves the same standard. If linking to external sites is a product feature, show an interstitial page that displays the destination instead of redirecting silently.","title":"Better still: do not accept URLs at all"},{"body":"Build the test table from transformations browsers actually apply: //host, backslashes, tabs and newlines inside the slashes or scheme, userinfo, suffix lookalikes, uppercase hosts, ports, the https:host form, javascript: and data: schemes, and percent-encoded slashes if any later component decodes them. Assert both the decision and the exact Location header. Run the same inputs through every place that redirects, including logout and error pages, because one unvalidated handler is enough. Log rejected values: repeated rejections are often the first visible sign that someone is testing phishing links against your login page.","title":"Test with a browser's eyes"}],"takeaway":"Accept a redirect target only if it is a path starting with exactly one slash or an https URL whose exact host is allow-listed; reject backslashes and control characters first and fall back to a fixed page.","title":"Open redirects: accept a single-slash path or an allow-listed host, not any URL that parses","unitID":"security-web","wrongAnswers":["url.Parse rejects it, so the handler returns a 500","Browsers resolve it to /evil.example on the same host"]},{"conceptTag":"security.http-headers","designGuide":{"cautions":["HSTS includeSubDomains and preload are hard to undo; raise them deliberately.","Cached HTML that contains a nonce shares that nonce across visitors."],"cost":"16 random bytes and a few header writes per response, plus the one-time work of moving inline handlers into nonce-tagged scripts.","family":"security","flow":["Generate nonce","Set headers first","Tag trusted scripts","Report, then enforce"],"ratings":[],"strengths":["Injected scripts without the nonce do not run even if escaping fails.","One middleware gives every response the same baseline policy."]},"hint":"Think about what an attacker learns by viewing one of your pages.","id":"security.http-headers","introduction":"Response headers turn browser features into policy: which scripts may run, whether the page may be framed, whether a response may be reinterpreted as another content type, how much of the URL leaks to other sites and whether plain HTTP is ever acceptable again. None of them fixes a bug in your handlers. They limit what an escaping mistake, an injected script or a hostile frame can do, so they belong in one middleware that wraps every response.","nuance":"A nonce is a bearer value: anyone who knows it can tag their own script. A fresh random value per response cannot be learned in advance or replayed later.","objective":"Write middleware that sets a nonce-based Content-Security-Policy and the other baseline security headers, and roll them out without breaking pages or locking in HSTS preload by accident.","question":"Why must the CSP script nonce change on every response instead of being fixed per deployment?","references":["https://cheatsheetseries.owasp.org/cheatsheets/HTTP_Headers_Cheat_Sheet.html","https://cheatsheetseries.owasp.org/cheatsheets/Content_Security_Policy_Cheat_Sheet.html","https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy","https://www.rfc-editor.org/rfc/rfc6797"],"reviewAnswer":"A reused nonce can be copied into injected scripts","reviewPrompt":"Why is a CSP nonce per response?","sections":[{"body":"Content-Security-Policy restricts where scripts, styles, frames and other resources may come from; with a strict script-src an injected <script> tag does not run. Strict-Transport-Security tells the browser to use HTTPS for this host for max-age seconds, so a network attacker cannot downgrade a later visit. X-Content-Type-Options: nosniff stops browsers from deciding that a text/plain or image response is really HTML or script. The frame-ancestors directive of CSP controls which origins may embed the page, which defeats clickjacking; X-Frame-Options: DENY is the legacy equivalent for old browsers, and a browser that enforces frame-ancestors ignores it when both are sent. Referrer-Policy limits how much of the current URL is sent in the Referer header. Leave out X-XSS-Protection: the filter it controlled is gone from modern browsers and could itself be abused.","title":"What each header defends against"},{"body":"The middleware draws a 128-bit nonce from crypto/rand for every response, sets all headers before calling the next handler and stores the nonce in the request context. The handler renders it into the one script tag it trusts. To show what CSP adds, a bug elsewhere has marked a stored comment as template.HTML, so an injected script tag reaches the page. Two requests go through httptest, and the program prints the first response with the random nonce masked.","code":"package main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"crypto/rand\"\n\t\"encoding/base64\"\n\t\"fmt\"\n\t\"html/template\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strings\"\n)\n\ntype nonceKey struct{}\n\nfunc newNonce() string {\n\tb := make([]byte, 16)\n\trand.Read(b) // never returns an error; crashes the program if the OS source fails\n\treturn base64.RawURLEncoding.EncodeToString(b)\n}\n\n// securityHeaders sets the policy before the inner handler writes anything.\nfunc securityHeaders(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tnonce := newNonce()\n\t\th := w.Header()\n\t\th.Set(\"Content-Security-Policy\", \"default-src 'self'; script-src 'nonce-\"+nonce+\"'; \"+\n\t\t\t\"object-src 'none'; base-uri 'none'; frame-ancestors 'none'\")\n\t\th.Set(\"Strict-Transport-Security\", \"max-age=31536000; includeSubDomains\")\n\t\th.Set(\"X-Content-Type-Options\", \"nosniff\")\n\t\th.Set(\"X-Frame-Options\", \"DENY\")\n\t\th.Set(\"Referrer-Policy\", \"strict-origin-when-cross-origin\")\n\t\tnext.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), nonceKey{}, nonce)))\n\t})\n}\n\nvar page = template.Must(template.New(\"page\").Parse(\n\t`<script nonce=\"{{.Nonce}}\">start()</script><p>{{.Comment}}</p>`))\n\nfunc handler(w http.ResponseWriter, r *http.Request) {\n\tnonce, _ := r.Context().Value(nonceKey{}).(string)\n\tvar buf bytes.Buffer\n\terr := page.Execute(&buf, map[string]any{\n\t\t\"Nonce\": nonce,\n\t\t// A bug elsewhere marked stored user input as trusted HTML.\n\t\t\"Comment\": template.HTML(`<script>steal()</script>`),\n\t})\n\tif err != nil {\n\t\thttp.Error(w, \"render failed\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\tbuf.WriteTo(w)\n}\n\nfunc nonceFrom(csp string) string {\n\t_, rest, _ := strings.Cut(csp, \"'nonce-\")\n\tnonce, _, _ := strings.Cut(rest, \"'\")\n\treturn nonce\n}\n\nfunc main() {\n\th := securityHeaders(http.HandlerFunc(handler))\n\tvar nonces []string\n\tfor range 2 {\n\t\trec := httptest.NewRecorder()\n\t\th.ServeHTTP(rec, httptest.NewRequest(\"GET\", \"https://example.com/\", nil))\n\t\tnonce := nonceFrom(rec.Header().Get(\"Content-Security-Policy\"))\n\t\tif len(nonces) == 0 {\n\t\t\tfor _, name := range []string{\"Content-Security-Policy\", \"Strict-Transport-Security\",\n\t\t\t\t\"X-Content-Type-Options\", \"X-Frame-Options\", \"Referrer-Policy\"} {\n\t\t\t\tfmt.Printf(\"%s: %s\\n\", name, strings.Replace(rec.Header().Get(name), nonce, \"<nonce>\", 1))\n\t\t\t}\n\t\t\tfmt.Println(\"body:\", strings.Replace(rec.Body.String(), nonce, \"<nonce>\", 1))\n\t\t}\n\t\tnonces = append(nonces, nonce)\n\t}\n\tfmt.Println(\"nonce length:\", len(nonces[0]))\n\tfmt.Println(\"fresh nonce per response:\", nonces[0] != nonces[1])\n}","language":"go","title":"Headers middleware with a per-request nonce","walkthrough":"script-src lists only the nonce, so a browser runs the script tag that carries it and refuses the injected one, which has no nonce and could not have guessed it; that is defense in depth on top of the escaping lesson, not a replacement. default-src 'self' covers other resource types, object-src 'none' disables plugins and base-uri 'none' stops an injected <base> tag from redirecting relative script URLs. The handler renders into a buffer first, so a template error becomes a clean 500 instead of half a page. The 16 random bytes become 22 base64url characters, which need no escaping inside an HTML attribute, and the second response gets a different value. Headers are set before next runs because header changes after WriteHeader are ignored."},{"body":"A nonce works only if an attacker cannot predict or reuse it, so generate one per response, never per process or per user, and do not let a CDN cache HTML that contains it, or every visitor shares one value. Static pages cannot carry a fresh nonce; allow their inline scripts by hash ('sha256-...') instead. Under this policy inline event handlers such as onclick and javascript: URLs are blocked, so move that code into nonce-tagged scripts. Introduce a new policy as Content-Security-Policy-Report-Only with a report-to or report-uri endpoint, read the violations for a release or two, then enforce it. Keep the policy string in one place in code, so a page that needs an exception gets a reviewed, narrow change instead of 'unsafe-inline'.","title":"CSP in practice: nonces, caching and a report-only rollout"},{"body":"Browsers ignore Strict-Transport-Security on plain-HTTP responses, so sending it on every response is harmless; it takes effect after the first HTTPS visit. Start with a short max-age such as 300 seconds, raise it to a year once every page and API works over HTTPS, and add includeSubDomains only when every subdomain, including internal tools and forgotten marketing hosts, serves valid HTTPS. The preload directive asks browser vendors to ship your domain in a built-in HTTPS-only list. Removal takes months to reach users, and meanwhile any subdomain without a working certificate is unreachable for everyone, so preload is a deliberate, owner-approved step, never a default in shared middleware. If TLS terminates at a load balancer, set HSTS there or here, but in exactly one place.","title":"HSTS: start short, preload last"},{"body":"In Gin the policy is a middleware registered with r.Use before any route. c.Header sets a response header, c.Set stores the nonce for handlers and c.HTML renders through html/template, which escapes the nonce attribute like any other value. Register it on the engine rather than on a route group so that 404 and recovery responses carry the headers too, then assert them in a router test.","code":"func SecurityHeaders() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tnonce := newNonce()\n\t\tc.Set(\"cspNonce\", nonce)\n\t\tc.Header(\"Content-Security-Policy\", \"default-src 'self'; script-src 'nonce-\"+nonce+\"'; \"+\n\t\t\t\"object-src 'none'; base-uri 'none'; frame-ancestors 'none'\")\n\t\tc.Header(\"Strict-Transport-Security\", \"max-age=31536000; includeSubDomains\")\n\t\tc.Header(\"X-Content-Type-Options\", \"nosniff\")\n\t\tc.Header(\"X-Frame-Options\", \"DENY\")\n\t\tc.Header(\"Referrer-Policy\", \"strict-origin-when-cross-origin\")\n\t\tc.Next()\n\t}\n}\n\n// In a handler:\n// c.HTML(http.StatusOK, \"page.tmpl\", gin.H{\"Nonce\": c.GetString(\"cspNonce\")})","language":"go","title":"The same middleware in Gin","walkthrough":"This fragment runs in your own Gin service and reuses newNonce from the program. c.Next runs the rest of the chain after the headers are set, so a handler can still override one header for one route, which is where a reviewed exception belongs. Gin builds its 404 chain from the engine's global middleware, so unmatched routes get these headers as well."},{"body":"Test headers as the program does: send requests through the full handler chain with httptest and compare each header with an exact expected string, masking only the nonce. Include an error page, a redirect, a static file and a 404, since those responses most often bypass middleware. Check that two responses never share a nonce and that the nonce in the header equals the one in the page. For pages whose URLs carry secrets, such as password-reset links, send Referrer-Policy: no-referrer on that response. In review, treat any new 'unsafe-inline', 'unsafe-eval', wildcard source or HSTS preload as a security change that needs its own justification.","title":"Test and review the headers"}],"takeaway":"Set CSP with a fresh per-response nonce, nosniff, frame-ancestors plus X-Frame-Options, Referrer-Policy and a gradually raised HSTS in one outer middleware, and treat preload as a separate, deliberate decision.","title":"Security headers: a per-request CSP nonce, HSTS, nosniff, frame-ancestors and Referrer-Policy","unitID":"security-web","wrongAnswers":["Browsers reject a nonce they have already seen","The nonce is a hash of the script body it allows"]},{"conceptTag":"security.secrets-redaction","designGuide":{"cautions":["Unexported fields bypass fmt methods, and encoding/json skips them silently.","Redacted hides only the userinfo password, not tokens in the query string."],"cost":"A small wrapper type, a Reveal call at each use site and one canary test per output channel. It does not protect memory, core dumps or values already copied into plain strings.","family":"security","flow":["Load once at startup","Wrap in a Secret type","Reveal at point of use","Canary-test every sink"],"ratings":[],"strengths":["Careless log lines and %+v dumps print a placeholder instead of the value.","Every intentional use is a searchable Reveal call."]},"hint":"fmt reaches field values through reflection; consider which values reflection may call methods on.","id":"security.secrets-redaction","introduction":"Most leaked credentials are not stolen from a vault; they are printed. A startup line that logs the configuration with %+v, an error that wraps a connection string, a debug endpoint that dumps settings: each copies the secret into log storage that more people can read, for longer, than the secret store itself. Make printing safe by default and make revealing the value an explicit, searchable call.","nuance":"fmt cannot invoke Format, String or Error on unexported fields, so it prints their contents directly; encoding/json, by contrast, skips such fields entirely.","objective":"Wrap credentials in a Secret type that redacts itself in fmt, slog and JSON, redact credentials in URLs, and load secrets with errors that name the source but never the value.","question":"A Secret type implements Format and String, but another struct holds it in an unexported field. What does %+v print for that struct?","references":["https://pkg.go.dev/log/slog#LogValuer","https://pkg.go.dev/fmt#Formatter","https://pkg.go.dev/net/url#URL.Redacted","https://cheatsheetseries.owasp.org/cheatsheets/Secrets_Management_Cheat_Sheet.html"],"reviewAnswer":"fmt skips its methods and prints the raw value","reviewPrompt":"Secret in an unexported field?","sections":[{"body":"Trace a database password through a typical service. It is read from the environment into a Config struct; the struct is logged at startup so operators can see what was loaded; the password is placed in a connection URL; and when the database is down, the URL appears in a wrapped error that is logged on every retry. None of these steps looks like a leak in review. The log pipeline then ships each line to an aggregator, to backups and perhaps to a vendor, where access rules and retention are looser than in your secret store. Once the value is there, the only safe response is rotation. Prevention works best at the type level: if the value cannot print itself, the careless log line stays harmless.","title":"Follow a password from config to log line"},{"body":"Secret keeps its value in an unexported field and implements four interfaces, because different encoders take different paths. fmt.Formatter covers every fmt verb, including %x and %q, and takes precedence over String and GoString. slog.LogValuer is resolved by slog handlers when a Secret is an attribute value. json.Marshaler covers JSON log handlers and API responses that embed the struct. String remains for code that asks for a fmt.Stringer directly. The program pushes a fake canary value through each path and checks whether it survived.","code":"package main\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n\t\"net/url\"\n\t\"strings\"\n)\n\nconst redacted = \"[REDACTED]\"\n\n// Secret holds a credential. Every formatting path prints a placeholder;\n// only Reveal returns the value, so each real use is visible in review.\ntype Secret struct{ value string }\n\nfunc NewSecret(v string) Secret { return Secret{value: v} }\n\nfunc (s Secret) Reveal() string { return s.value }\n\nfunc (Secret) String() string                { return redacted }\nfunc (Secret) Format(f fmt.State, verb rune) { io.WriteString(f, redacted) }\nfunc (Secret) LogValue() slog.Value          { return slog.StringValue(redacted) }\nfunc (Secret) MarshalJSON() ([]byte, error)  { return json.Marshal(redacted) }\n\ntype Config struct {\n\tAddr       string\n\tDBPassword Secret\n}\n\nfunc main() {\n\tconst canary = \"canary-7f3a\" // a fake value we can search for\n\n\ttype plain struct{ Addr, DBPassword string }\n\tfmt.Println(\"plain field leaks:\", strings.Contains(fmt.Sprintf(\"%+v\", plain{\":8080\", canary}), canary))\n\n\tcfg := Config{Addr: \":8080\", DBPassword: NewSecret(canary)}\n\tfmt.Printf(\"%+v\\n\", cfg)\n\tfmt.Printf(\"%#v %x %q\\n\", cfg.DBPassword, cfg.DBPassword, cfg.DBPassword)\n\n\ttype hidden struct{ token Secret }\n\tfmt.Println(\"unexported field leaks:\", strings.Contains(fmt.Sprintf(\"%+v\", hidden{NewSecret(canary)}), canary))\n\n\tvar buf bytes.Buffer\n\topts := &slog.HandlerOptions{ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {\n\t\tif a.Key == slog.TimeKey && len(groups) == 0 {\n\t\t\treturn slog.Attr{} // drop the timestamp so the output is stable\n\t\t}\n\t\treturn a\n\t}}\n\tfor _, h := range []slog.Handler{slog.NewJSONHandler(&buf, opts), slog.NewTextHandler(&buf, opts)} {\n\t\tslog.New(h).Info(\"config loaded\", \"db_password\", cfg.DBPassword, \"config\", cfg)\n\t}\n\tfmt.Print(buf.String())\n\n\tdsn, err := url.Parse(\"postgres://orders:\" + canary + \"@db.internal.example:5432/orders\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(\"url String leaks:\", strings.Contains(dsn.String(), canary))\n\tfmt.Println(fmt.Errorf(\"connect %s: %w\", dsn.Redacted(), errors.New(\"connection refused\")))\n\tfmt.Println(\"leak found in any output:\", strings.Contains(buf.String(), canary))\n}","language":"go","title":"A Secret type that redacts every formatting path","walkthrough":"A plain string field prints verbatim under %+v. Config.DBPassword is an exported field, so fmt calls Secret.Format on it and every verb prints [REDACTED]. The hidden struct shows the trap: fmt cannot invoke methods on unexported fields, so it falls back to reflection and prints {token:{value:canary-7f3a}}. The JSON handler resolves db_password through LogValue and encodes the nested config with json.Marshal, which calls MarshalJSON; the text handler formats the nested struct with %+v, which reaches Format. url.URL.String includes the password, while Redacted replaces it with xxxxx before the URL enters an error string. The final line confirms the canary never reached the log buffer."},{"body":"The type protects only the paths it implements, so learn the rules that bypass it. fmt and encoding/json both ignore methods on unexported struct fields: fmt prints the raw contents and json silently skips the field. slog resolves LogValuer on attribute values and inside groups, not inside struct fields, so a nested Secret relies on MarshalJSON in a JSON handler and on Format in a text handler. Calling Reveal hands out a plain string that no longer protects itself, so do it at the last moment, inside the call that needs it, such as building a driver configuration. Reflection-based dumpers and some third-party loggers walk struct fields directly; check how each one you use prints a value. If configuration is decoded from a file, give Secret an UnmarshalText method so it never exists as a plain string field. Keep the method name distinctive, so a search for Reveal lists every intentional use.","title":"Know which path each encoder takes"},{"body":"Connection strings carry credentials in the userinfo part, and url.URL.String prints them. Redacted replaces only the password; it does not touch tokens in the query string, so keep API keys in headers, because proxies and access logs record URLs. The net/http client already replaces the password with *** in the *url.Error it returns, but errors you build with fmt.Errorf get no such help. When loading, accept either NAME or NAME_FILE, the convention for secrets that container platforms mount as files; reject both being set, trim the trailing newline that editors add, and refuse empty values. Every error names the variable or the file, never the content.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\ntype Secret struct{ value string }\n\nfunc (s Secret) Reveal() string              { return s.value }\nfunc (Secret) Format(f fmt.State, verb rune) { io.WriteString(f, \"[REDACTED]\") }\n\n// loadSecret reads NAME_FILE (a mounted secret file) or NAME, never both.\n// Errors name the variable or the path, never the value.\nfunc loadSecret(name string) (Secret, error) {\n\tpath, fromFile := os.LookupEnv(name + \"_FILE\")\n\tvalue, fromEnv := os.LookupEnv(name)\n\tswitch {\n\tcase fromFile && fromEnv:\n\t\treturn Secret{}, fmt.Errorf(\"%s: set %s or %s_FILE, not both\", name, name, name)\n\tcase fromFile:\n\t\tb, err := os.ReadFile(path)\n\t\tif err != nil {\n\t\t\treturn Secret{}, fmt.Errorf(\"%s_FILE: %w\", name, err)\n\t\t}\n\t\tvalue = strings.TrimRight(string(b), \"\\r\\n\")\n\tcase !fromEnv:\n\t\treturn Secret{}, fmt.Errorf(\"%s: not set; provide %s or %s_FILE\", name, name, name)\n\t}\n\tif value == \"\" {\n\t\treturn Secret{}, fmt.Errorf(\"%s: empty value\", name)\n\t}\n\treturn Secret{value: value}, nil\n}\n\nfunc main() {\n\tdir, err := os.MkdirTemp(\"\", \"secret-load\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer os.RemoveAll(dir)\n\tpath := filepath.Join(dir, \"db_password\")\n\tif err := os.WriteFile(path, []byte(\"canary-7f3a\\n\"), 0o600); err != nil {\n\t\tpanic(err)\n\t}\n\n\tos.Unsetenv(\"ORDERS_DB_PASSWORD\")\n\tos.Setenv(\"ORDERS_DB_PASSWORD_FILE\", path)\n\tdb, err := loadSecret(\"ORDERS_DB_PASSWORD\")\n\tfmt.Println(db, err, db.Reveal() == \"canary-7f3a\")\n\n\tos.Setenv(\"ORDERS_DB_PASSWORD\", \"also-set\")\n\t_, err = loadSecret(\"ORDERS_DB_PASSWORD\")\n\tfmt.Println(err)\n\n\tos.Unsetenv(\"ORDERS_API_TOKEN\")\n\tos.Unsetenv(\"ORDERS_API_TOKEN_FILE\")\n\t_, err = loadSecret(\"ORDERS_API_TOKEN\")\n\tfmt.Println(err)\n\n\tos.Setenv(\"ORDERS_API_TOKEN\", \"\")\n\t_, err = loadSecret(\"ORDERS_API_TOKEN\")\n\tfmt.Println(err)\n}","language":"go","title":"Redact URLs and fail loudly without the value","walkthrough":"This second program compiles as shown; run it in your own environment. It writes a test secret under os.TempDir with mode 0600 and points ORDERS_DB_PASSWORD_FILE at it. The first line prints [REDACTED] <nil> true: the loaded Secret hides itself while Reveal still returns the canary. Setting both forms is ambiguous and fails; a missing variable fails with a message that tells the operator exactly what to provide; an empty value is treated as an error rather than silently connecting without a password. Call loadSecret during startup so a bad deployment fails before it accepts traffic."},{"body":"Environment variables are convenient but broad: every child process inherits them, Linux exposes them through /proc to the same user and to root, crash reporters often capture them, and os.Unsetenv after reading does not erase copies a supervisor already holds. Mounted files can carry tight permissions, can be rotated by replacing the file, and keep the value out of the environment. A secret manager adds audit trails, short-lived credentials and automatic rotation, at the cost of a network dependency during startup. Whatever the source, load secrets once at startup into Secret values, re-read files on a signal or timer if rotation must not need a restart, and never log a prefix of the value: a few characters of a short password narrow guessing considerably. To correlate rotations, log a key ID or version number, which is not secret.","title":"Choose where secrets live"},{"body":"Add one test per output channel: build the real Config from a canary value, run the code that logs it at startup, render the error your connection code produces, encode the debug endpoint's JSON, and fail if the canary appears anywhere. The test is cheap and catches the regression that matters most, a new credential field added as a plain string. Keep a log-pipeline scrubber for known token formats as a second line of defense, but treat it as a backstop: by the time it runs, the secret has already left the process.","code":"func TestStartupLogDoesNotLeak(t *testing.T) {\n\tconst canary = \"canary-7f3a\"\n\tvar buf bytes.Buffer\n\tlogger := slog.New(slog.NewJSONHandler(&buf, nil))\n\tcfg := Config{Addr: \":8080\", DBPassword: NewSecret(canary)}\n\n\tlogStartup(logger, cfg) // the function production calls at boot\n\n\tif strings.Contains(buf.String(), canary) {\n\t\tt.Fatalf(\"secret leaked into the startup log: %s\", buf.String())\n\t}\n}","language":"go","title":"Prove it with a canary test","walkthrough":"This _test.go fragment belongs in your service's package and runs with go test in your own environment; it also needs the bytes, log/slog, strings and testing imports. logStartup stands for whatever function production calls at boot. Testing that function rather than a copy of it is what makes the test meaningful. Printing the buffer on failure is safe here because the canary is not a real credential."}],"takeaway":"Wrap credentials in a type whose every formatting path prints a placeholder, keep secret fields exported or explicitly encoded, redact URLs before they reach errors, and fail at startup with messages that name the source, never the value.","title":"Keep secrets out of logs and errors with a type that refuses to print itself","unitID":"security-operations","wrongAnswers":["[REDACTED], because Format is always called first","Nothing, because unexported fields are omitted"]},{"conceptTag":"security.constant-time","designGuide":{"cautions":["ConstantTimeCompare returns immediately when lengths differ.","Lookups, error messages and metrics around the comparison can still leak."],"cost":"One hash and a full-length comparison per check, negligible next to a network round trip. The real cost is reviewing the surrounding path, which tests cannot do for you.","family":"security","flow":["Hash to a fixed length","Look up by public ID","Compare with crypto/subtle","Return one error"],"ratings":[],"strengths":["Removes the per-byte oracle that makes long tokens guessable.","Digest comparison also hides the length and lets you store only hashes."]},"hint":"Think about what happens to the response time as more of the guess is correct.","id":"security.constant-time","introduction":"A comparison that stops at the first differing byte takes longer the more of the guess is correct. Against a token, an API key or a MAC tag, that turns an impossible search over the whole value into a byte-by-byte search an attacker can run with enough repeated requests. Constant time here means time that depends only on public facts, such as the length, and never on the contents of the secret.","nuance":"The result is correct; the leak is in the duration. Work that grows with the matching prefix lets an attacker recover the token one byte at a time.","objective":"Recognize timing-dependent comparisons and replace them with crypto/subtle or hmac.Equal over fixed-size digests, including the lookup and error paths around them.","question":"Comparing a presented API token with == returns the right answer. Why is it still a vulnerability?","references":["https://pkg.go.dev/crypto/subtle#ConstantTimeCompare","https://pkg.go.dev/crypto/hmac#Equal","https://pkg.go.dev/crypto/subtle#WithDataIndependentTiming"],"reviewAnswer":"It stops early, so timing reveals the correct prefix","reviewPrompt":"Why not == for API tokens?","sections":[{"body":"To guess a 20-byte token blindly, an attacker faces 256^20 candidates. If the server's comparison returns as soon as one byte differs, each response time hints at how many leading bytes were right. The attacker then fixes one position at a time: at most 256 candidates per byte across 20 bytes, a few thousand guesses, each repeated enough times to average out network noise. The difference per byte is tiny, but repeated measurements from a nearby network position, such as another tenant in the same cloud region, can resolve it. Go's == on strings and bytes.Equal make no timing promise and do stop early, so they are the wrong tool for secrets even though they are the right tool for everything else.","title":"Why an early return is an oracle"},{"body":"Timing is noisy in a demo, so the program counts the bytes a naive loop examines, which is what its running time tracks. It then shows the standard tools: subtle.ConstantTimeCompare for equal-length values, a SHA-256 digest step that removes the length signal, and hmac.Equal for MAC tags computed with a test-only key.","code":"package main\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/sha256\"\n\t\"crypto/subtle\"\n\t\"fmt\"\n)\n\n// naiveEqual mirrors a hand-written loop (and what == may do): it stops at\n// the first mismatch. steps counts the bytes examined, a stand-in for time.\nfunc naiveEqual(a, b []byte) (equal bool, steps int) {\n\tif len(a) != len(b) {\n\t\treturn false, 0\n\t}\n\tfor i := range a {\n\t\tsteps++\n\t\tif a[i] != b[i] {\n\t\t\treturn false, steps\n\t\t}\n\t}\n\treturn true, steps\n}\n\n// tokenMatches hashes both sides first, so the comparison always runs over\n// two 32-byte digests no matter how long the presented token is.\nfunc tokenMatches(presented string, storedDigest [32]byte) bool {\n\td := sha256.Sum256([]byte(presented))\n\treturn subtle.ConstantTimeCompare(d[:], storedDigest[:]) == 1\n}\n\nfunc main() {\n\tsecret := []byte(\"tok_4f9c2a7e81b3d605\") // a test token, 20 bytes\n\tguesses := []string{\n\t\t\"xxxxxxxxxxxxxxxxxxxx\", // nothing right\n\t\t\"tok_xxxxxxxxxxxxxxxx\", // public prefix right\n\t\t\"tok_4f9c2axxxxxxxxxx\", // ten bytes right\n\t\t\"tok_4f9c2a7e81b3d605\", // all right\n\t}\n\tfor _, g := range guesses {\n\t\teq, steps := naiveEqual(secret, []byte(g))\n\t\tfmt.Printf(\"naive  %s equal=%-5t bytes examined=%d\\n\", g, eq, steps)\n\t}\n\n\t// Equal-length inputs: work depends only on the length.\n\tfmt.Println(\"subtle full match:\", subtle.ConstantTimeCompare(secret, []byte(guesses[3])))\n\tfmt.Println(\"subtle ten bytes right:\", subtle.ConstantTimeCompare(secret, []byte(guesses[2])))\n\t// Different lengths return 0 immediately: the length itself can leak.\n\tfmt.Println(\"subtle short guess:\", subtle.ConstantTimeCompare(secret, []byte(\"tok_\")))\n\n\tstored := sha256.Sum256(secret)\n\tfmt.Println(\"digest match:\", tokenMatches(\"tok_4f9c2a7e81b3d605\", stored))\n\tfmt.Println(\"digest short guess:\", tokenMatches(\"tok_\", stored))\n\n\tkey := []byte(\"test-only-hmac-key-0123456789abc\")\n\tmac := func(msg string) []byte {\n\t\tm := hmac.New(sha256.New, key)\n\t\tm.Write([]byte(msg))\n\t\treturn m.Sum(nil)\n\t}\n\treceived := mac(\"order=42;amount=1999\")\n\tfmt.Println(\"hmac.Equal valid:\", hmac.Equal(mac(\"order=42;amount=1999\"), received))\n\tfmt.Println(\"hmac.Equal altered:\", hmac.Equal(mac(\"order=42;amount=1\"), received))\n\tfmt.Println(\"hmac.Equal truncated:\", hmac.Equal(mac(\"order=42;amount=1999\"), received[:16]))\n}","language":"go","title":"Measure the work instead of the nanoseconds","walkthrough":"The naive loop examines 1, 5, 11 and 20 bytes: its work grows with the correct prefix, and that growth is the oracle. subtle.ConstantTimeCompare XORs every byte pair and ORs the results, so for equal lengths its work does not depend on content; it returns the int 1 or 0, not a bool. The short guess returns 0 immediately, because the documented guarantee covers contents, not length. tokenMatches hashes the presented value first, so every comparison runs over two 32-byte digests whatever the caller sends. hmac.Equal is ConstantTimeCompare(...) == 1; the truncated tag fails because its length differs."},{"body":"ConstantTimeCompare returns at once when lengths differ, and its documentation says so. For tokens you issue in a fixed format, the length is public anyway. For values whose length is secret or chosen by someone else, such as a shared webhook secret or a legacy API key, compare digests: SHA-256 of either side is always 32 bytes. Hashing also lets you store only the digest, so a database read does not hand out working credentials; the token-design lesson builds on that. A fast hash is enough only for high-entropy values. Passwords need the slow, salted hashing of the password-storage lesson, because a fast digest of a guessable value is itself guessable. For MAC tags, compute the expected tag over the received message and compare the full length: code that compares only as many bytes as the client sent accepts a one-byte tag after at most 256 tries.","title":"Fixed-size digests close the length channel"},{"body":"A constant-time compare inside a variable-time path still leaks. Look at the code around it: a lookup that returns early when a key ID is unknown, a database query with the secret in its WHERE clause, different messages or status codes for no such key and wrong key, and metrics labeled by failure reason all reveal information. Look credentials up by a public identifier or by the digest of the secret, compare in constant time, and return one generic error. When the identifier is unknown, compare against a dummy digest so both paths do the same work.","code":"func (s *KeyStore) Authenticate(keyID, presented string) (Principal, error) {\n\tgot := sha256.Sum256([]byte(presented))\n\trec, found := s.byID[keyID] // keyID is public, e.g. the prefix of the API key\n\twant := s.dummy             // a random digest, so unknown IDs do the same work\n\tif found {\n\t\twant = rec.Digest\n\t}\n\tif subtle.ConstantTimeCompare(got[:], want[:]) != 1 || !found {\n\t\treturn Principal{}, errUnauthorized // one error for every failure\n\t}\n\treturn rec.Principal, nil\n}","language":"go","title":"The comparison is not the only branch","walkthrough":"This fragment shows the shape of an API key check; KeyStore, Principal and errUnauthorized belong to your service, and it runs in your own environment. The map lookup by a public key ID may take variable time because the ID is not secret. Both branches hash and compare, and the found check comes after the comparison, so an unknown ID and a wrong secret are indistinguishable in both result and work."},{"body":"Unit tests cannot prove constant time, and a benchmark that shows equal averages on a laptop says little about a loaded production CPU. Treat it as a review rule instead: every comparison of a token, MAC, API key, signature or password hash uses subtle.ConstantTimeCompare, hmac.Equal or a library verifier that does, over fixed-length inputs, followed by a single error path. Search for == and bytes.Equal near names such as token, secret, signature and digest. On arm64, subtle.WithDataIndependentTiming (Go 1.24) enables the processor's data-independent-timing mode for code that is already written in constant time; it does not repair variable-time code, and most services do not need it. Rate limiting the endpoint helps as well, because the attack needs many requests.","title":"Review it; do not try to benchmark it"}],"takeaway":"Compare secrets with crypto/subtle or hmac.Equal over fixed-size digests, look them up by a public ID or by their hash, and give every failure the same error and the same amount of work.","title":"Compare secrets in constant time: an early return reveals how much of a guess was right","unitID":"security-operations","wrongAnswers":["It compares string pointers, like == on Java strings","It is slow enough to enable a denial of service"]},{"conceptTag":"security.aead-encryption","designGuide":{"cautions":["A repeated nonce under one key breaks both confidentiality and integrity.","Ciphertext length reveals plaintext length, and encrypted columns are not searchable."],"cost":"33 bytes per record, one AES-GCM operation per read and write, and a re-encryption job plus a key inventory for every rotation.","family":"security","flow":["Pick the current key ID","Seal with a random nonce","Bind header + record ID","Rotate, re-encrypt, retire"],"ratings":[],"strengths":["Tampering, row swaps and wrong keys all fail with one authentication error.","Key IDs turn rotation into a gradual migration instead of a flag day."]},"hint":"Ask which input to Open the attacker cannot change by copying bytes between rows.","id":"security.aead-encryption","introduction":"Encrypting a column protects data in backups, replicas and database dumps, but only if the record format answers more than which key to use. The crypto-purposes lesson explains why encryption must be authenticated. This lesson builds the record envelope: AES-GCM through crypto/cipher, a fresh random nonce per seal, a key ID that survives rotation, and additional data that ties each ciphertext to the row it belongs to.","nuance":"The tag covers the additional data, so opening with the victim's record ID fails authentication even though the copied ciphertext itself is intact.","objective":"Seal application records with AES-GCM so that tampering, row swapping and key rotation are handled explicitly, and explain why a repeated nonce breaks GCM.","question":"An attacker with database write access copies their own encrypted bank details into a victim's row. What stops the application from accepting them?","references":["https://pkg.go.dev/crypto/cipher#NewGCMWithRandomNonce","https://pkg.go.dev/crypto/cipher#AEAD","https://www.rfc-editor.org/rfc/rfc5116","https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html"],"reviewAnswer":"A ciphertext then opens only in the row it was sealed for","reviewPrompt":"Why pass the record ID as AD?","sections":[{"body":"Picture customers' bank details stored encrypted in a table, and three attackers. One reads a backup and should learn nothing but lengths. One flips bits in a ciphertext, hoping to change a value without knowing it. One can write to the database, perhaps through a bug elsewhere, and copies the ciphertext from their own row into a victim's row, so that the victim's next payout goes to the attacker's account. AES-GCM, an AEAD, handles the first two: it hides the plaintext, and its tag check rejects any modification. The third needs context. Passing the record ID as additional data, which is authenticated but not encrypted, means a ciphertext opens only in the row it was sealed for.","title":"What a record envelope must guarantee"},{"body":"The envelope is version(1) || keyID(4) || nonce(12) || ciphertext || tag(16). cipher.NewGCMWithRandomNonce, added in Go 1.24, draws the nonce from crypto/rand and prepends it, so the caller cannot pass a stale one. The header and the record ID together form the additional data. The program prints sizes, booleans and errors rather than ciphertext, so its output is identical on every run even though keys and nonces are random.","code":"package main\n\nimport (\n\t\"bytes\"\n\t\"crypto/aes\"\n\t\"crypto/cipher\"\n\t\"crypto/rand\"\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"fmt\"\n)\n\nconst version = 1\n\n// Keyring maps a key ID to an AEAD. Sealed records carry the ID that\n// encrypted them, so old records stay readable after rotation.\ntype Keyring struct {\n\tcurrent uint32\n\taeads   map[uint32]cipher.AEAD\n}\n\nfunc (k *Keyring) Add(id uint32, key []byte) error {\n\tblock, err := aes.NewCipher(key) // 32-byte key: AES-256\n\tif err != nil {\n\t\treturn err\n\t}\n\taead, err := cipher.NewGCMWithRandomNonce(block) // nonce generated and prepended for us\n\tif err != nil {\n\t\treturn err\n\t}\n\tk.aeads[id], k.current = aead, id\n\treturn nil\n}\n\n// header is version(1) || keyID(4). It is authenticated together with the\n// record ID, so neither can be changed without failing Open.\nfunc additionalData(header []byte, recordID string) []byte {\n\treturn append(bytes.Clone(header), recordID...)\n}\n\nfunc (k *Keyring) Seal(recordID string, plaintext []byte) []byte {\n\theader := binary.BigEndian.AppendUint32([]byte{version}, k.current)\n\treturn k.aeads[k.current].Seal(header, nil, plaintext, additionalData(header, recordID))\n}\n\nfunc (k *Keyring) Open(recordID string, blob []byte) ([]byte, error) {\n\tif len(blob) < 5 || blob[0] != version {\n\t\treturn nil, errors.New(\"unsupported record format\")\n\t}\n\tid := binary.BigEndian.Uint32(blob[1:5])\n\taead, ok := k.aeads[id]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unknown key ID %d\", id)\n\t}\n\treturn aead.Open(nil, nil, blob[5:], additionalData(blob[:5], recordID))\n}\n\nfunc newKey() []byte {\n\tkey := make([]byte, 32)\n\trand.Read(key) // never fails; crashes the program if the OS source does\n\treturn key\n}\n\nfunc must[T any](v T, err error) T {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}\n\nfunc main() {\n\tring := &Keyring{aeads: map[uint32]cipher.AEAD{}}\n\tif err := ring.Add(1, newKey()); err != nil {\n\t\tpanic(err)\n\t}\n\tpii := []byte(`{\"iban\":\"DE89370400440532013000\"}`)\n\tblob := ring.Seal(\"customer-17\", pii)\n\tfmt.Printf(\"plaintext %d bytes, sealed %d bytes\\n\", len(pii), len(blob))\n\tfmt.Println(\"two seals differ:\", !bytes.Equal(blob, ring.Seal(\"customer-17\", pii)))\n\n\tgot, err := ring.Open(\"customer-17\", blob)\n\tfmt.Println(\"open own row:\", string(got), err)\n\t_, err = ring.Open(\"customer-99\", blob)\n\tfmt.Println(\"open copied to another row:\", err)\n\n\ttampered := bytes.Clone(blob)\n\ttampered[len(tampered)-20] ^= 0x01\n\t_, err = ring.Open(\"customer-17\", tampered)\n\tfmt.Println(\"open after one flipped bit:\", err)\n\n\tif err := ring.Add(2, newKey()); err != nil { // rotate: new writes use key 2\n\t\tpanic(err)\n\t}\n\tfresh := ring.Seal(\"customer-18\", pii)\n\t_, err = ring.Open(\"customer-17\", blob)\n\tfmt.Println(\"new record key ID:\", binary.BigEndian.Uint32(fresh[1:5]), \"old record still opens:\", err == nil)\n\tdelete(ring.aeads, 1) // retiring a key before re-encrypting its rows\n\t_, err = ring.Open(\"customer-17\", blob)\n\tfmt.Println(\"after retiring key 1:\", err)\n\n\t// TEST PATH ONLY: a fixed nonce, to show why nonces must never repeat.\n\tblock := must(aes.NewCipher(newKey()))\n\tgcm := must(cipher.NewGCM(block))\n\tfixedNonce := make([]byte, gcm.NonceSize())\n\tp1, p2 := []byte(\"transfer 100 to acct 1111\"), []byte(\"transfer 900 to acct 6666\")\n\tc1 := gcm.Seal(nil, fixedNonce, p1, nil)\n\tc2 := gcm.Seal(nil, fixedNonce, p2, nil)\n\trecovered := make([]byte, len(p1))\n\tfor i := range recovered { // an observer who knows p1 learns p2\n\t\trecovered[i] = c1[i] ^ c2[i] ^ p1[i]\n\t}\n\tfmt.Printf(\"nonce reuse recovers: %s\\n\", recovered)\n}","language":"go","title":"Seal, open, rotate and fail","walkthrough":"The 33-byte plaintext becomes 66 bytes: 5 of header, 12 of nonce and 16 of tag. Two seals of the same value differ because each draws a new nonce. Opening under customer-99 fails with cipher: message authentication failed, the same error as a flipped bit; GCM cannot say which part was wrong, and should not. additionalData clones the header before appending, so the append cannot write into the buffer Seal is about to fill. After key 2 is added, new records carry key ID 2 while the old record still opens with key 1, and deleting key 1 too early makes it unreadable. The final block is a labeled test path: cipher.NewGCM with a fixed all-zero nonce. Two messages sealed under one nonce let anyone who knows the first recover the second with XOR."},{"body":"GCM is counter mode plus a polynomial MAC. Reusing a nonce under the same key reuses the keystream, so the XOR of two ciphertexts equals the XOR of their plaintexts, as the test path shows. Worse, two messages under one nonce let an attacker solve for the authentication subkey and forge valid tags for messages of their choosing. A random 96-bit nonce keeps collisions negligible only within a budget: the NewGCMWithRandomNonce documentation says a key must not encrypt more than 2^32 messages. Counters avoid randomness but are hard to keep unique across replicas, restarts and restored backups. For very high volumes per key, rotate by message count or time, derive separate keys per tenant, or use XChaCha20-Poly1305 from golang.org/x/crypto/chacha20poly1305, whose 192-bit nonces can be chosen at random for far more messages.","title":"Nonces must never repeat under one key"},{"body":"A key ID in every record is what makes rotation possible: readers choose the key from the record and writers always use the current key. Rotation then has three phases. Add the new key everywhere and make it current. Re-encrypt old rows in a background job that opens and reseals each one. Retire the old key only when a count of rows by key ID reaches zero; retiring first, as the program shows, turns rotation into data loss. In production the keys usually come from a key management service through envelope encryption: a master key held by the service encrypts the data keys your application uses, so rotating the master key re-wraps a few small data keys instead of rewriting every row. The key ID is not secret, but it is authenticated through the additional data, so editing it in place fails the tag check.","title":"Rotation is a data migration, not a config change"},{"body":"An AEAD hides content, not size: here the ciphertext is always 33 bytes longer than the plaintext, so pad values whose length is sensitive. Encrypted columns cannot be searched or indexed; if you need equality lookups, store a separate HMAC of the normalized value under a different key, accepting that it reveals which rows are equal. Additional data must be unambiguous: when it combines several variable-length fields, length-prefix each one so that (ab, c) and (a, bc) differ. On an authentication failure, return an error and raise an alert; never log ciphertext next to plaintext, and never fall back to returning unauthenticated bytes. Tests should flip every byte of a sealed record, move it to another ID, open it after rotation and after retirement, and assert that a configured key is exactly 32 bytes.","title":"Limits and the review checklist"}],"takeaway":"Use an AEAD with a fresh random nonce per seal, authenticate a versioned header and the record ID as additional data, carry a key ID for rotation, and retire a key only after no record uses it.","title":"Encrypt records with AES-GCM: random nonces, a key ID, and the record ID as additional data","unitID":"security-operations","wrongAnswers":["A random nonce makes every ciphertext unique","AES-256 keys are too long to brute-force"]},{"conceptTag":"security.password-storage","designGuide":{"cautions":["Memory cost times concurrency can exhaust a server unless it is bounded.","bcrypt compares only the first 72 bytes of a password."],"cost":"Tens of milliseconds of CPU and tens of MiB of memory per login by design, plus a semaphore, a rate limiter and a lazy migration path to maintain.","family":"security","flow":["Parse and bound params","Verify in constant time","Rehash on policy change","Throttle and answer alike"],"ratings":[],"strengths":["Parameters travel with each hash, so the policy can rise without resets.","Uniform errors and uniform work hide which accounts exist."]},"hint":"Upgrading needs an input that the database deliberately does not keep.","id":"security.password-storage","introduction":"The crypto-purposes lesson establishes that passwords need a slow, salted, memory-hard function. The operational questions come next: how to store the parameters with each hash so they can change later, how to upgrade old hashes without forcing resets, how to budget memory when many users log in at once, and how to keep the login endpoint from telling an attacker which accounts exist.","nuance":"A password hash cannot be reversed, so only a login that has just verified the password holds the plaintext needed to hash it again with new parameters.","objective":"Hash passwords with argon2id in a self-describing PHC-style string, upgrade parameters at login, handle bcrypt's 72-byte limit and keep login failures indistinguishable.","question":"Your argon2id policy raised the memory cost. How do existing accounts get the stronger hash without a forced reset?","references":["https://pkg.go.dev/golang.org/x/crypto/argon2#IDKey","https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html","https://www.rfc-editor.org/rfc/rfc9106","https://pkg.go.dev/golang.org/x/crypto/bcrypt#GenerateFromPassword"],"reviewAnswer":"At a successful login, when the plaintext is available","reviewPrompt":"When can an old hash be upgraded?","sections":[{"body":"Assume an attacker eventually holds the users table. They can then guess offline as fast as their hardware allows, with no rate limit. A random per-user salt stops them from attacking every account at once with precomputed tables, and argon2id's memory cost makes each guess expensive on GPUs and custom hardware, not just on CPUs. Your parameters will need to rise as hardware improves, so every stored hash must record the algorithm, version and costs that produced it. The PHC string format does that in one column, for example $argon2id$v=19$m=19456,t=2,p=1$salt$hash, with salt and hash in unpadded standard base64.","title":"Design for the day the table leaks"},{"body":"The program uses deliberately small costs so it finishes in milliseconds. It registers an account under an old policy, rejects an unknown email and a wrong password with the same error, upgrades the stored hash on a successful login, refuses a stored row with hostile parameters, and then shows bcrypt's length limit.","code":"package main\n\nimport (\n\t\"bytes\"\n\t\"crypto/rand\"\n\t\"crypto/subtle\"\n\t\"encoding/base64\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"golang.org/x/crypto/argon2\"\n\t\"golang.org/x/crypto/bcrypt\"\n)\n\ntype Params struct {\n\tMemory  uint32 // KiB\n\tTime    uint32 // passes\n\tThreads uint8\n}\n\n// Demo-sized costs so the example runs in milliseconds. Production\n// values are in the next section.\nvar (\n\toldPolicy = Params{Memory: 4 * 1024, Time: 1, Threads: 1}\n\tpolicy    = Params{Memory: 8 * 1024, Time: 2, Threads: 1}\n)\n\nvar b64 = base64.RawStdEncoding\n\nfunc hash(password string, p Params) string {\n\tsalt := make([]byte, 16)\n\trand.Read(salt)\n\tkey := argon2.IDKey([]byte(password), salt, p.Time, p.Memory, p.Threads, 32)\n\treturn fmt.Sprintf(\"$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s\",\n\t\targon2.Version, p.Memory, p.Time, p.Threads, b64.EncodeToString(salt), b64.EncodeToString(key))\n}\n\nvar errMalformed = errors.New(\"malformed password hash\")\n\nfunc parse(encoded string) (p Params, salt, key []byte, err error) {\n\tparts := strings.Split(encoded, \"$\")\n\tif len(parts) != 6 || parts[1] != \"argon2id\" || parts[2] != fmt.Sprintf(\"v=%d\", argon2.Version) {\n\t\treturn p, nil, nil, errMalformed\n\t}\n\tif _, err := fmt.Sscanf(parts[3], \"m=%d,t=%d,p=%d\", &p.Memory, &p.Time, &p.Threads); err != nil {\n\t\treturn p, nil, nil, errMalformed\n\t}\n\t// A stored row is input too: refuse costs that would exhaust the server.\n\tif p.Memory < 1024 || p.Memory > 256*1024 || p.Time < 1 || p.Time > 10 || p.Threads < 1 {\n\t\treturn p, nil, nil, errMalformed\n\t}\n\tif salt, err = b64.DecodeString(parts[4]); err != nil || len(salt) < 16 {\n\t\treturn p, nil, nil, errMalformed\n\t}\n\tif key, err = b64.DecodeString(parts[5]); err != nil || len(key) != 32 {\n\t\treturn p, nil, nil, errMalformed\n\t}\n\treturn p, salt, key, nil\n}\n\n// verify reports whether password matches, and whether the stored hash\n// should be replaced because the policy has moved on.\nfunc verify(password, encoded string) (ok, rehash bool, err error) {\n\tp, salt, want, err := parse(encoded)\n\tif err != nil {\n\t\treturn false, false, err\n\t}\n\tgot := argon2.IDKey([]byte(password), salt, p.Time, p.Memory, p.Threads, uint32(len(want)))\n\tok = subtle.ConstantTimeCompare(got, want) == 1\n\treturn ok, ok && p != policy, nil\n}\n\nvar errInvalidLogin = errors.New(\"invalid email or password\")\n\nfunc login(users map[string]string, email, password string) error {\n\tstored, found := users[email]\n\tif !found {\n\t\thash(password, policy) // spend the same work for unknown accounts\n\t\treturn errInvalidLogin\n\t}\n\tok, rehash, err := verify(password, stored)\n\tif err != nil || !ok {\n\t\treturn errInvalidLogin // same message for every failure reason\n\t}\n\tif rehash {\n\t\tusers[email] = hash(password, policy) // the only moment the plaintext is available\n\t}\n\treturn nil\n}\n\n// params returns the \"$argon2id$v=19$m=...,t=...,p=...\" part; salt and key stay private.\nfunc params(encoded string) string { return strings.Join(strings.Split(encoded, \"$\")[:4], \"$\") }\n\nfunc main() {\n\tusers := map[string]string{\"member@example.com\": hash(\"correct horse battery\", oldPolicy)}\n\tfmt.Println(\"stored:\", params(users[\"member@example.com\"]))\n\n\tfmt.Println(\"unknown email:\", login(users, \"unknown@example.com\", \"guess\"))\n\tfmt.Println(\"wrong password:\", login(users, \"member@example.com\", \"guess\"))\n\tfmt.Println(\"correct password:\", login(users, \"member@example.com\", \"correct horse battery\"))\n\tfmt.Println(\"rehashed to:\", params(users[\"member@example.com\"]))\n\t_, rehash, _ := verify(\"correct horse battery\", users[\"member@example.com\"])\n\tfmt.Println(\"needs rehash now:\", rehash)\n\t_, _, err := verify(\"x\", \"$argon2id$v=19$m=4194304,t=1,p=1$c2FsdHNhbHRzYWx0c2FsdA$AAAA\") // 4 GiB\n\tfmt.Println(\"hostile parameters:\", err)\n\n\tlong := bytes.Repeat([]byte(\"a\"), 72)\n\th, err := bcrypt.GenerateFromPassword(long, bcrypt.MinCost) // MinCost only for the demo\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(\"bcrypt ignores byte 73+:\", bcrypt.CompareHashAndPassword(h, append(long, \"anything\"...)) == nil)\n\t_, err = bcrypt.GenerateFromPassword(append(long, 'a'), bcrypt.MinCost)\n\tfmt.Println(\"bcrypt 73-byte input:\", err)\n}","language":"go","title":"Hash, verify and upgrade in one login path","walkthrough":"hash draws a 16-byte salt from crypto/rand and encodes the costs next to the result; params prints only the parameter prefix, because salt and hash change on every run. parse checks every field and bounds the costs, because a stored row is input too: m=4194304 would demand 4 GiB per login. verify recomputes with the stored parameters and compares with subtle.ConstantTimeCompare. login spends a full hash on unknown emails, returns one error for every failure, and rehashes when the policy has changed, the only moment the plaintext is available. bcrypt.GenerateFromPassword rejects a 73-byte password, yet CompareHashAndPassword silently uses only the first 72 bytes, so any suffix matches."},{"body":"The demo's 8 MiB and two passes are far too cheap. The OWASP Password Storage Cheat Sheet gives argon2id with m=19456 KiB (19 MiB), t=2 and p=1 as a minimum, with equivalent trade-offs such as m=47104 KiB and t=1. RFC 9106 recommends t=1 with 2 GiB, or t=3 with 64 MiB when memory is tighter, both with four lanes. Benchmark on production hardware and aim for a verification of tens of milliseconds, then multiply the memory by the concurrency you allow: fifty simultaneous logins at 64 MiB need more than 3 GiB. Bound concurrent hashing with a semaphore so a burst of login attempts produces fast errors instead of an out-of-memory crash. For existing bcrypt systems, OWASP recommends a cost of at least 10.","code":"// 8 slots x 19 MiB caps hashing memory near 152 MiB, whatever the traffic.\nvar hashSlots = make(chan struct{}, 8)\n\nfunc verifyBounded(ctx context.Context, password, encoded string) (ok, rehash bool, err error) {\n\tselect {\n\tcase hashSlots <- struct{}{}:\n\t\tdefer func() { <-hashSlots }()\n\tcase <-ctx.Done():\n\t\treturn false, false, ctx.Err() // the handler answers 503, not 500\n\t}\n\treturn verify(password, encoded)\n}","language":"go","title":"Production parameters and a memory budget","walkthrough":"This fragment wraps the verify function from the program and runs in your own service. The buffered channel is a counting semaphore: a login takes a slot before hashing and returns it afterwards. When every slot is busy, the request waits until its context deadline, so overload produces quick, visible errors rather than unbounded memory growth. Size the slot count as the memory you can spare divided by the m parameter."},{"body":"Because parameters live in the hash, upgrading is lazy: when verification succeeds and the stored parameters differ from the current policy, hash the password again and save it. Accounts that never log in keep old hashes; to retire a weak scheme completely, require a reset for them after a deadline. The same dispatch migrates algorithms: a stored value that begins with $2a$ or $2b$ is bcrypt, so verify it with bcrypt and store an argon2id hash on success. bcrypt reads at most 72 bytes, and UTF-8 passphrases reach that sooner than their character count suggests. Since the x/crypto implementation refuses long passwords when hashing but not when comparing, cap password length at registration in bytes and remember that a longer password typed at login is checked on its first 72 bytes only. Moving to argon2id is simpler than pre-hashing passwords for bcrypt.","title":"Upgrade old hashes, including bcrypt"},{"body":"A login endpoint leaks through its differences. Return the same message and status for an unknown email, a wrong password and a malformed stored hash, and spend the same work on each: the program hashes the submitted password even when no account exists, because skipping the hash makes unknown emails answer measurably faster. Registration and password-reset flows can reveal the same fact, so give them neutral responses such as: if the address exists, we sent a link. Hashing slows offline guessing only; online guessing needs throttling. Limit attempts per account and per source address, for example with golang.org/x/time/rate limiters held in a bounded cache, and prefer growing delays to hard lockouts that let anyone lock a victim out. Log failures with the account ID, never the submitted password, and test that every failure returns identical bodies and that rehashing happens exactly once.","title":"One answer for every failure, and fewer guesses"}],"takeaway":"Store argon2id hashes with their parameters, bound the costs when parsing and the memory when verifying, rehash on a successful login when the policy changes, and make every login failure look and cost the same.","title":"Store passwords with argon2id: encoded parameters, rehash on login, one answer for every failure","unitID":"security-operations","wrongAnswers":["Decrypt each stored hash and hash it again","Old hashes verify under the new parameters anyway"]},{"conceptTag":"security.token-design","designGuide":{"cautions":["Signed tokens stay valid until exp unless verifiers check a deny-list.","HMAC verifiers share the signing key and can therefore mint tokens."],"cost":"A lookup per request for opaque tokens, or key distribution, short lifetimes and a refresh flow for signed ones; either way, a table of hostile test tokens to maintain.","family":"security","flow":["Choose opaque or signed","Store hashes, rotate","Pin alg, verify bytes","Check exp, nbf, iss, aud"],"ratings":[],"strengths":["Hashed opaque tokens are useless from a leaked table and revoke instantly.","A strict verifier rejects whole families of attacks by construction."]},"hint":"Consider who wrote the header and what they would choose.","id":"security.token-design","introduction":"The identity-authorization lesson says to validate a token's full contract before trusting the principal it names. This lesson designs the tokens themselves. Opaque tokens are random strings that mean nothing without a lookup, so revocation is immediate. Signed tokens carry their claims and verify without a lookup, so revocation is hard and every claim check is your job. Both need expiry, rotation and a plan for theft.","nuance":"The header is attacker-controlled input. Honoring it enables alg none and key-confusion attacks, so the expected algorithm must come from configuration bound to the key.","objective":"Choose between opaque and signed tokens, store opaque tokens as hashes with rotation and reuse detection, and verify HMAC-signed JWTs with a pinned algorithm and checked claims.","question":"A verifier reads alg from the token header and uses it to decide how to check the signature. What is wrong with that?","references":["https://www.rfc-editor.org/rfc/rfc8725","https://www.rfc-editor.org/rfc/rfc7519","https://www.rfc-editor.org/rfc/rfc9700","https://pkg.go.dev/crypto/hmac#Equal"],"reviewAnswer":"The verifier's configuration, never the token header","reviewPrompt":"Who picks the JWT algorithm?","sections":[{"body":"If the service that issues a token is the only one that checks it, as with browser sessions or first-party API keys, use an opaque token: 32 random bytes, encoded, with all state kept on the server. Revocation is a row update, and the token reveals nothing about the user if it leaks into a log. Signed tokens such as JWTs earn their complexity when many services must verify independently without calling the issuer. The price is that a stolen signed token stays valid until it expires, unless every verifier also consults a revocation list, which brings the lookup back. Keep signed access tokens short-lived, minutes rather than days, and pair them with an opaque refresh token that the issuer can revoke.","title":"Pick the token by who verifies it"},{"body":"The store keeps only SHA-256 digests and is keyed by them, so a leaked table cannot be replayed and the lookup never compares the secret itself, as the constant-time lesson recommends. Refresh tokens rotate: each use returns a new token and marks the old one used. A second use of the same token means two parties hold it, so the whole family descending from that login is revoked. The clock is an injected function, which keeps expiry deterministic.","code":"package main\n\nimport (\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar (\n\terrInvalid = errors.New(\"invalid token\")\n\terrExpired = errors.New(\"token expired\")\n\terrRevoked = errors.New(\"token revoked\")\n\terrReuse   = errors.New(\"refresh token reused: family revoked\")\n)\n\ntype record struct {\n\tuserID  string\n\tfamily  string // all tokens descended from one login\n\texpires time.Time\n\tused    bool\n}\n\n// Store keeps only SHA-256 digests. A leaked table cannot be replayed,\n// and lookups never compare the secret itself.\ntype Store struct {\n\tbyHash  map[[32]byte]*record\n\trevoked map[string]bool // revoked families\n\tnow     func() time.Time\n}\n\nconst prefix = \"gfr_\" // a recognizable prefix helps secret scanners\n\nfunc (s *Store) issue(userID, family string, ttl time.Duration) string {\n\traw := make([]byte, 32)\n\trand.Read(raw)\n\ttoken := prefix + base64.RawURLEncoding.EncodeToString(raw)\n\ts.byHash[sha256.Sum256([]byte(token))] = &record{userID, family, s.now().Add(ttl), false}\n\treturn token\n}\n\nfunc (s *Store) lookup(token string) (*record, error) {\n\tif !strings.HasPrefix(token, prefix) || len(token) != len(prefix)+43 {\n\t\treturn nil, errInvalid\n\t}\n\tr, ok := s.byHash[sha256.Sum256([]byte(token))]\n\tswitch {\n\tcase !ok:\n\t\treturn nil, errInvalid\n\tcase s.revoked[r.family]:\n\t\treturn nil, errRevoked\n\tcase !s.now().Before(r.expires):\n\t\treturn nil, errExpired\n\t}\n\treturn r, nil\n}\n\n// Rotate exchanges a refresh token for a new one. Presenting an already\n// used token means two parties hold it, so the whole family is revoked.\nfunc (s *Store) Rotate(token string) (string, error) {\n\tr, err := s.lookup(token)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif r.used {\n\t\ts.revoked[r.family] = true\n\t\treturn \"\", errReuse\n\t}\n\tr.used = true\n\treturn s.issue(r.userID, r.family, 30*24*time.Hour), nil\n}\n\nfunc main() {\n\tnow := time.Date(2026, 11, 18, 9, 0, 0, 0, time.UTC)\n\ts := &Store{byHash: map[[32]byte]*record{}, revoked: map[string]bool{}, now: func() time.Time { return now }}\n\n\tt1 := s.issue(\"user-42\", \"login-1\", 30*24*time.Hour)\n\tfmt.Println(\"token length:\", len(t1), \"stored digest bytes:\", len(sha256.Sum256([]byte(t1))))\n\tr, err := s.lookup(t1)\n\tfmt.Println(\"lookup:\", r.userID, err)\n\taltered := []byte(t1)\n\taltered[10] ^= 0x01 // change one character\n\t_, err = s.lookup(string(altered))\n\tfmt.Println(\"altered:\", err)\n\n\tt2, err := s.Rotate(t1)\n\tfmt.Println(\"rotated:\", t2 != t1, err)\n\t_, err = s.Rotate(t1) // an attacker replays the stolen original\n\tfmt.Println(\"replay old:\", err)\n\t_, err = s.Rotate(t2) // the legitimate client is logged out too\n\tfmt.Println(\"use new:\", err)\n\n\tt3 := s.issue(\"user-7\", \"login-2\", time.Hour)\n\tnow = now.Add(61 * time.Minute)\n\t_, err = s.lookup(t3)\n\tfmt.Println(\"after 61 minutes:\", err)\n}","language":"go","title":"Opaque tokens: store the digest, rotate on use","walkthrough":"issue draws 32 bytes from crypto/rand and adds a gfr_ prefix, giving 47 characters; a recognizable prefix lets secret scanners and log scrubbers find leaked tokens. lookup rejects the wrong shape before hashing, then checks family revocation and expiry against the injected clock. A one-character change misses the map entirely. Rotate returns a new token; replaying the original afterwards triggers reuse detection, which also invalidates the legitimate client's new token and forces a fresh login, a deliberate trade of convenience for containing theft. Moving the fixed clock forward 61 minutes expires the one-hour token."},{"body":"When you must verify JWTs, prefer a maintained library and configure it strictly. The program shows what strict means using only the standard library: the algorithm is pinned by configuration, the header may contain only alg, typ and kid, the signature is checked over the exact received bytes before any claim is parsed, and exp is mandatory. It runs ten tokens, from valid to hostile, against a fixed clock and a test-only key.","code":"package main\n\nimport (\n\t\"bytes\"\n\t\"crypto/hmac\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"slices\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar b64 = base64.RawURLEncoding.Strict()\n\ntype header struct {\n\tAlg string `json:\"alg\"`\n\tTyp string `json:\"typ\"`\n\tKid string `json:\"kid\"`\n}\n\ntype Claims struct {\n\tIss string   `json:\"iss\"`\n\tSub string   `json:\"sub\"`\n\tAud audience `json:\"aud\"`\n\tExp *int64   `json:\"exp\"`\n\tNbf *int64   `json:\"nbf\"`\n}\n\n// audience accepts the two RFC 7519 shapes: \"a\" or [\"a\", \"b\"].\ntype audience []string\n\nfunc (a *audience) UnmarshalJSON(b []byte) error {\n\tvar one string\n\tif json.Unmarshal(b, &one) == nil {\n\t\t*a = audience{one}\n\t\treturn nil\n\t}\n\treturn json.Unmarshal(b, (*[]string)(a))\n}\n\n// Verifier accepts exactly one algorithm, issuer and audience.\ntype Verifier struct {\n\tKeys     map[string][]byte // kid -> HMAC key\n\tIssuer   string\n\tAudience string\n\tLeeway   time.Duration\n\tNow      func() time.Time\n}\n\nfunc base64URLOnly(s string) bool {\n\tfor _, c := range s {\n\t\tif !('a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' || c == '-' || c == '_') {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn s != \"\"\n}\n\nfunc (v *Verifier) Verify(token string) (*Claims, error) {\n\tparts := strings.Split(token, \".\")\n\tif len(parts) != 3 || !base64URLOnly(parts[0]) || !base64URLOnly(parts[1]) {\n\t\treturn nil, errors.New(\"malformed token\")\n\t}\n\tvar h header\n\tif err := decodeStrict(parts[0], &h); err != nil {\n\t\treturn nil, errors.New(\"malformed header\")\n\t}\n\tif h.Alg != \"HS256\" { // pinned by configuration, never chosen by the token\n\t\treturn nil, fmt.Errorf(\"unsupported alg %q\", h.Alg)\n\t}\n\tif h.Typ != \"at+jwt\" {\n\t\treturn nil, fmt.Errorf(\"unexpected typ %q\", h.Typ)\n\t}\n\tkey, ok := v.Keys[h.Kid]\n\tif !ok {\n\t\treturn nil, errors.New(\"unknown key ID\")\n\t}\n\tsig, err := b64.DecodeString(parts[2])\n\tif !base64URLOnly(parts[2]) || err != nil || !hmac.Equal(sig, mac(key, parts[0]+\".\"+parts[1])) {\n\t\treturn nil, errors.New(\"invalid signature\")\n\t}\n\t// Only bytes that passed the signature check are parsed as claims.\n\tvar c Claims\n\tpayload, err := b64.DecodeString(parts[1])\n\tif err != nil || json.Unmarshal(payload, &c) != nil {\n\t\treturn nil, errors.New(\"malformed claims\")\n\t}\n\tnow := v.Now()\n\tswitch {\n\tcase c.Exp == nil:\n\t\treturn nil, errors.New(\"missing exp\")\n\tcase !now.Before(time.Unix(*c.Exp, 0).Add(v.Leeway)):\n\t\treturn nil, errors.New(\"token expired\")\n\tcase c.Nbf != nil && now.Add(v.Leeway).Before(time.Unix(*c.Nbf, 0)):\n\t\treturn nil, errors.New(\"token not valid yet\")\n\tcase c.Iss != v.Issuer:\n\t\treturn nil, errors.New(\"wrong issuer\")\n\tcase !slices.Contains(c.Aud, v.Audience):\n\t\treturn nil, errors.New(\"wrong audience\")\n\t}\n\treturn &c, nil\n}\n\n// decodeStrict rejects header fields this verifier does not understand,\n// such as \"crit\", \"jku\" or \"jwk\".\nfunc decodeStrict(part string, v any) error {\n\traw, err := b64.DecodeString(part)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdec := json.NewDecoder(bytes.NewReader(raw))\n\tdec.DisallowUnknownFields()\n\treturn dec.Decode(v)\n}\n\nfunc mac(key []byte, signingInput string) []byte {\n\tm := hmac.New(sha256.New, key)\n\tm.Write([]byte(signingInput))\n\treturn m.Sum(nil)\n}\n\n// sign builds test tokens, including deliberately hostile ones.\nfunc sign(key []byte, h, claims string) string {\n\tin := b64.EncodeToString([]byte(h)) + \".\" + b64.EncodeToString([]byte(claims))\n\treturn in + \".\" + b64.EncodeToString(mac(key, in))\n}\n\nfunc main() {\n\tkey := []byte(\"test-only-key-32-bytes-long-0001\") // test key, never a real secret\n\tnow := time.Date(2026, 11, 18, 12, 0, 0, 0, time.UTC)\n\tv := &Verifier{Keys: map[string][]byte{\"k1\": key}, Issuer: \"https://auth.example\", Audience: \"orders-api\",\n\t\tLeeway: 30 * time.Second, Now: func() time.Time { return now }}\n\n\thdr := `{\"alg\":\"HS256\",\"typ\":\"at+jwt\",\"kid\":\"k1\"}`\n\tclaims := func(aud string, exp, nbf int64) string {\n\t\treturn fmt.Sprintf(`{\"iss\":\"https://auth.example\",\"sub\":\"user-42\",\"aud\":%s,\"exp\":%d,\"nbf\":%d}`, aud, exp, nbf)\n\t}\n\tt := now.Unix()\n\tgood := sign(key, hdr, claims(`[\"orders-api\",\"billing-api\"]`, t+300, t-60))\n\tparts := strings.Split(good, \".\")\n\tforgedPayload := b64.EncodeToString([]byte(claims(`\"orders-api\"`, t+86400, t-60)))\n\n\tcases := []struct{ name, token string }{\n\t\t{\"valid\", good},\n\t\t{\"alg none\", b64.EncodeToString([]byte(`{\"alg\":\"none\",\"typ\":\"at+jwt\",\"kid\":\"k1\"}`)) + \".\" + parts[1] + \".\"},\n\t\t{\"alg switch\", sign(key, `{\"alg\":\"HS512\",\"typ\":\"at+jwt\",\"kid\":\"k1\"}`, claims(`\"orders-api\"`, t+300, t-60))},\n\t\t{\"jku header\", sign(key, `{\"alg\":\"HS256\",\"typ\":\"at+jwt\",\"kid\":\"k1\",\"jku\":\"https://evil.example/k\"}`, claims(`\"orders-api\"`, t+300, t-60))},\n\t\t{\"unknown kid\", sign(key, `{\"alg\":\"HS256\",\"typ\":\"at+jwt\",\"kid\":\"k9\"}`, claims(`\"orders-api\"`, t+300, t-60))},\n\t\t{\"edited payload\", parts[0] + \".\" + forgedPayload + \".\" + parts[2]},\n\t\t{\"expired\", sign(key, hdr, claims(`\"orders-api\"`, t-31, t-600))},\n\t\t{\"not yet valid\", sign(key, hdr, claims(`\"orders-api\"`, t+600, t+120))},\n\t\t{\"other audience\", sign(key, hdr, claims(`\"billing-api\"`, t+300, t-60))},\n\t\t{\"missing exp\", sign(key, hdr, `{\"iss\":\"https://auth.example\",\"sub\":\"user-42\",\"aud\":\"orders-api\"}`)},\n\t}\n\tfor _, c := range cases {\n\t\tgot, err := v.Verify(c.token)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"%-15s rejected: %v\\n\", c.name, err)\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Printf(\"%-15s accepted: sub=%s aud=%v\\n\", c.name, got.Sub, got.Aud)\n\t}\n}","language":"go","title":"A strict verifier for HMAC-signed tokens","walkthrough":"This second program compiles as shown; run it in your own environment and it prints one accepted line followed by nine rejections. alg none and HS512 fail the pinned algorithm before any key is chosen, which is the defense against algorithm switching: the token never selects how it is verified. decodeStrict rejects the jku header, closing the family of attacks that inject keys or key URLs. The edited payload keeps the original signature and fails hmac.Equal. exp 31 seconds in the past exceeds the 30-second leeway; nbf two minutes ahead fails; an audience list without orders-api fails; and a token without exp is refused instead of treated as eternal. base64URLOnly matters because Go's base64 decoders ignore newlines even in Strict mode."},{"body":"Give every token an absolute expiry and, for sessions, an idle timeout as well. Design revocation in from the start: for opaque tokens, delete or flag the record and revoke every family a user owns when the password changes; for signed tokens, keep lifetimes short or keep a deny-list of token IDs (jti) until their exp passes. Signing keys rotate through kid: publish the new key to verifiers first, start signing with it, and remove the old key only after the longest token lifetime has elapsed. Allow a clock-skew leeway of seconds, not hours. Use explicit typ values, such as at+jwt from RFC 9068 for access tokens, so an ID token or refresh token cannot be replayed where an access token is expected. Asymmetric algorithms such as EdDSA or ES256 let verifiers hold only public keys; with HMAC, every verifier can also mint tokens.","title":"Expiry, revocation and key rotation in production"},{"body":"Keep the ten cases from the verifier as table tests and add those a library might mishandle: alg in a different case, a kid that names a key meant for another purpose, an aud claim that is a number, exp as a float or a string, very long tokens, and a valid token presented to a different service. Go's encoding/json matches field names case-insensitively and keeps the last of duplicate keys, so another parser in your system might read a different exp or sub than you do; reject such payloads or make sure only one parser ever interprets the token. For opaque tokens, test expiry at the exact boundary, reuse detection, revocation after a password change, and that no code path stores or logs the raw token.","title":"Hostile tokens for the test suite"}],"takeaway":"Prefer hashed opaque tokens when the issuer is the verifier; when tokens must be signed, pin the algorithm, verify the exact bytes before parsing, require exp, and check iss, aud and nbf against an injected clock.","title":"Design tokens deliberately: hashed opaque tokens, strictly verified signed tokens, expiry and rotation","unitID":"security-operations","wrongAnswers":["Nothing, as long as the signature check itself is correct","Only alg none is dangerous; other values are safe"]},{"conceptTag":"security.fuzzing-parsers","designGuide":{"cautions":["Invariants define what fuzzing can find; a target that only parses finds only panics.","A limit on compressed size does not limit decompressed size."],"cost":"A fuzz test per parser, CPU time for scheduled fuzzing runs and committed corpus files; the hardening itself costs a few comparisons per field.","family":"security","flow":["Seed with real inputs","Assert invariants","Fuzz, minimize, commit","Cap lengths and inflation"],"ratings":[],"strengths":["Finds inputs you did not think of, often within seconds for small formats.","Saved failures become permanent regression tests that run with go test."]},"hint":"Two different byte strings can decode to the same value; which check compares bytes rather than values?","id":"security.fuzzing-parsers","introduction":"Every parser that reads bytes from outside the process is attack surface: upload formats, binary protocols, compressed bodies, custom headers. Unit tests check the inputs you thought of. Go's built-in fuzzer mutates seed inputs, guided by coverage, to find the ones you did not, such as a length field that points past the end or a non-canonical encoding that breaks a round trip.","nuance":"A non-minimal varint parses without panicking and within limits, but re-encoding it yields different bytes, so only the round-trip comparison fails.","objective":"Write a native Go fuzz test with seed inputs and real invariants for a binary parser, harden the parser against what it finds, and cap decompressed size with io.LimitReader.","question":"Which invariant in a parser's fuzz target catches a non-canonical length encoding that the other checks miss?","references":["https://go.dev/doc/security/fuzz/","https://pkg.go.dev/testing#F.Fuzz","https://pkg.go.dev/io#LimitReader","https://pkg.go.dev/net/http#MaxBytesReader"],"reviewAnswer":"Encode(Parse(b)) equals b whenever Parse succeeds","reviewPrompt":"Strongest parser fuzz invariant?","sections":[{"body":"Parsers fail in a few recurring ways. They trust a declared length and slice past the end of the buffer, which in Go is a panic rather than memory corruption; but an unrecovered panic in a background goroutine stops the whole process, and even net/http, which recovers handler panics, drops the connection. They allocate whatever a length field asks for, so a five-byte message can request gigabytes. They accept several encodings of the same value, so two components that parse the same bytes disagree, which matters when one of them checks a signature or a policy. And decompressors turn a small input into a huge output. Each of these failures corresponds to an invariant a fuzzer can check on every input.","title":"Where parsers break"},{"body":"The record format is a field count followed by tag, uvarint length and value for each field. Parse checks every length before slicing, caps the number and size of fields, rejects non-minimal varints and trailing bytes, and copies values so callers never alias the input buffer. The program runs Parse on the seeds a fuzz test would start from, shows the panic a naive parser hits, and inflates a gzip bomb through a size limit.","code":"package main\n\nimport (\n\t\"bytes\"\n\t\"compress/gzip\"\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n)\n\nconst (\n\tmaxFields   = 8\n\tmaxValueLen = 256\n)\n\nvar errMalformed = errors.New(\"malformed record\")\n\ntype Field struct {\n\tTag   byte\n\tValue []byte\n}\n\n// Parse decodes: count(1) then per field tag(1) || uvarint(len) || value.\n// Every length is checked before it is used, and only canonical\n// encodings are accepted, so Encode(Parse(b)) == b whenever Parse succeeds.\nfunc Parse(b []byte) ([]Field, error) {\n\tif len(b) == 0 || b[0] > maxFields {\n\t\treturn nil, fmt.Errorf(\"%w: field count\", errMalformed)\n\t}\n\tcount, b := int(b[0]), b[1:]\n\tfields := make([]Field, 0, count)\n\tfor range count {\n\t\tif len(b) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"%w: truncated tag\", errMalformed)\n\t\t}\n\t\ttag := b[0]\n\t\tn, k := binary.Uvarint(b[1:])\n\t\tswitch {\n\t\tcase k <= 0:\n\t\t\treturn nil, fmt.Errorf(\"%w: bad length\", errMalformed)\n\t\tcase k != len(binary.AppendUvarint(nil, n)):\n\t\t\treturn nil, fmt.Errorf(\"%w: non-minimal length\", errMalformed)\n\t\tcase n > maxValueLen:\n\t\t\treturn nil, fmt.Errorf(\"%w: value too long\", errMalformed)\n\t\tcase uint64(len(b)-1-k) < n:\n\t\t\treturn nil, fmt.Errorf(\"%w: truncated value\", errMalformed)\n\t\t}\n\t\tb = b[1+k:]\n\t\tfields = append(fields, Field{tag, bytes.Clone(b[:n])})\n\t\tb = b[n:]\n\t}\n\tif len(b) != 0 {\n\t\treturn nil, fmt.Errorf(\"%w: trailing bytes\", errMalformed)\n\t}\n\treturn fields, nil\n}\n\nfunc Encode(fields []Field) []byte {\n\tout := []byte{byte(len(fields))}\n\tfor _, f := range fields {\n\t\tout = append(out, f.Tag)\n\t\tout = binary.AppendUvarint(out, uint64(len(f.Value)))\n\t\tout = append(out, f.Value...)\n\t}\n\treturn out\n}\n\n// naiveParse trusts the declared length, the bug fuzzing finds first.\nfunc naiveParse(b []byte) (value []byte, err error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr = fmt.Errorf(\"panic: %v\", r)\n\t\t}\n\t}()\n\tn, k := binary.Uvarint(b[2:])\n\treturn b[2+k : 2+k+int(n)], nil\n}\n\n// readAtMost refuses to inflate more than limit bytes.\nfunc readAtMost(r io.Reader, limit int64) ([]byte, error) {\n\tdata, err := io.ReadAll(io.LimitReader(r, limit+1))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif int64(len(data)) > limit {\n\t\treturn nil, fmt.Errorf(\"decompressed body exceeds %d bytes\", limit)\n\t}\n\treturn data, nil\n}\n\nfunc main() {\n\tseeds := [][]byte{\n\t\t{2, 'n', 3, 'a', 'd', 'a', 'r', 1, 'x'},\n\t\t{1, 'n', 5, 'a', 'd'},\n\t\t{1, 'n', 0x80, 0x00},\n\t\t{1, 'n', 0xff, 0xff, 0xff, 0xff, 0x0f},\n\t\t{1, 'n', 1, 'a', 'z'},\n\t\t{9},\n\t}\n\tfor i, s := range seeds {\n\t\tfields, err := Parse(s)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"seed %d: %v\\n\", i, err)\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Printf(\"seed %d: %d fields, round trip %t\\n\", i, len(fields), bytes.Equal(Encode(fields), s))\n\t}\n\t_, err := naiveParse(seeds[1])\n\tfmt.Println(\"naive parser:\", err)\n\n\tvar bomb bytes.Buffer\n\tzw := gzip.NewWriter(&bomb)\n\tzw.Write(make([]byte, 16<<20)) // 16 MiB of zeros\n\tzw.Close()\n\tfmt.Println(\"compressed under 64 KiB:\", bomb.Len() < 64<<10)\n\tzr, err := gzip.NewReader(&bomb)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t_, err = readAtMost(zr, 1<<20)\n\tfmt.Println(\"inflate with 1 MiB limit:\", err)\n}","language":"go","title":"A hardened parser, its seeds and a gzip bomb","walkthrough":"Seed 0 parses and re-encodes to identical bytes. Seed 1 declares five value bytes but carries two. Seed 2 encodes the length 0 as 0x80 0x00, which binary.Uvarint accepts but Encode never produces. Seed 3 asks for about four billion bytes and is refused before any allocation. Seed 4 has a trailing byte and seed 5 claims nine fields. naiveParse trusts the length, and the recovered panic shows the slice bound it hit. The bomb is 16 MiB of zeros that compresses to well under 64 KiB; readAtMost reads through io.LimitReader with limit+1 bytes, so it can tell a body exactly at the limit from one over it, and refuses the latter."},{"body":"A fuzz test is a function FuzzXxx(*testing.F) in a _test.go file. f.Add registers seed inputs, and f.Fuzz receives the target, whose parameters after *testing.T must match the seed types. The target does not know the right answer for a random input; it states what must hold for every input. For a parser, three invariants catch most bugs: it never panics, its output is bounded by its input and its limits, and a successful parse re-encodes to exactly the same bytes.","code":"package record\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n)\n\nfunc FuzzParse(f *testing.F) {\n\tf.Add([]byte{2, 'n', 3, 'a', 'd', 'a', 'r', 1, 'x'}) // valid\n\tf.Add([]byte{1, 'n', 0x80, 0x00})                    // non-minimal length\n\tf.Add([]byte{1, 'n', 5, 'a', 'd'})                   // truncated value\n\tf.Add([]byte{})\n\tf.Fuzz(func(t *testing.T, data []byte) {\n\t\tfields, err := Parse(data) // invariant 1: never panics\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\ttotal := 0\n\t\tfor _, fl := range fields {\n\t\t\ttotal += len(fl.Value)\n\t\t}\n\t\t// invariant 2: bounded output, never larger than the input\n\t\tif len(fields) > maxFields || total > len(data) {\n\t\t\tt.Fatalf(\"%d fields, %d value bytes from %d input bytes\", len(fields), total, len(data))\n\t\t}\n\t\t// invariant 3: canonical round trip\n\t\tif enc := Encode(fields); !bytes.Equal(enc, data) {\n\t\t\tt.Fatalf(\"round trip changed %x into %x\", data, enc)\n\t\t}\n\t})\n}","language":"go","title":"The fuzz test: seeds plus invariants","walkthrough":"This _test.go fragment sits next to Parse and Encode in a package named record; run it with go test in your own environment. Without -fuzz, go test runs only the seeds and any files under testdata/fuzz/FuzzParse, so the fuzz test doubles as a cheap regression test. A panic anywhere in Parse fails the target, which is invariant one. The byte-count check fails if a bug ever reports more value bytes than were read. The round-trip check is the strongest of the three, and it holds only because Parse accepts canonical encodings alone."},{"body":"Fuzz one target at a time: -fuzz takes a regular expression that must match exactly one fuzz test in exactly one package. As an experiment, remove the non-minimal check from Parse and the matching seed from the test: on a laptop the fuzzer found the round-trip failure in under a second, minimized it, and wrote it to testdata/fuzz/FuzzParse, from where plain go test replays it. Commit those files; they are the regression tests for the bugs you fixed. Run the seeds on every commit, a short fuzzing budget on a schedule, and longer sessions after parser changes.","code":"# Seeds and saved failures only, as in every CI run:\ngo test ./record -run=FuzzParse\n\n# Generate new inputs for a fixed budget:\ngo test ./record -run='^$' -fuzz=FuzzParse -fuzztime=60s\n\n# Replay one saved failure while fixing it:\ngo test ./record -run=FuzzParse/c8edd71d506c459a","language":"bash","title":"Run it and keep what it finds","walkthrough":"Run these in your own module. The first command replays seeds and saved corpus files without generating anything. The second fuzzes for 60 seconds across all CPUs; inputs that expand coverage are cached under $GOCACHE/fuzz, not in the repository. In the experiment the report read: round trip changed 01308000 into 013000, that is count 1, tag 0x30 and the two-byte encoding of length zero that Encode shortens to one byte. The saved file starts with the line go test fuzz v1 followed by the input as a Go literal; the hash in its name will differ on your machine."},{"body":"Limits belong at every layer that can expand data. http.MaxBytesReader caps the compressed request body, but a gzip body inflates after that check, so wrap the decompressor in a LimitReader as readAtMost does and treat hitting the limit as an error rather than silently truncating. The net/http Transport transparently decompresses gzip responses it asked for, so outbound response bodies need the same cap. For zip archives, the sizes in the headers are claims made by whoever built the archive: limit the number of entries and the bytes read per entry and in total, and leave entry names to the path-traversal lesson. Never preallocate from a declared length without a cap. Fuzzing proves nothing about inputs it never reached, so check the seed run with go test -coverprofile and add seeds for the branches it misses.","title":"Bound decompression and allocation everywhere"}],"takeaway":"Give every parser of untrusted input a fuzz test with seeds and invariants (no panic, bounded output, canonical round trip), commit the failures it finds, and cap every declared length and every decompressed byte.","title":"Fuzz the parsers that read untrusted bytes, and bound what they may allocate or inflate","unitID":"security-operations","wrongAnswers":["The parser returns an error instead of panicking","The number of fields stays below the configured limit"]},{"conceptTag":"security.supply-chain","designGuide":{"cautions":["The checksum database proves consistency, not that code is benign.","Tool directives add tool dependencies to the application's module graph."],"cost":"A govulncheck step and a build-information gate in CI, plus reviewer time for every dependency update; keeping the defaults on costs nothing.","family":"security","flow":["Pin modules and tools","Verify sums, read-only","Scan reachable vulns","Audit binary build info"],"ratings":[],"strengths":["Reachability analysis keeps vulnerability reports short and actionable.","Embedded build information makes every shipped binary auditable after the fact."]},"hint":"The database is a transparent log of hashes; think about what a hash can and cannot say about code.","id":"security.supply-chain","introduction":"Most of the code in a Go binary was written by someone else. The toolchain provides strong defaults: go.sum pins exact module content, the checksum database exposes a module version that changed after publication, and every binary records the modules it was built from. Supply-chain security in Go is mostly about not weakening those defaults, and about reacting quickly and precisely when a dependency has a known vulnerability.","nuance":"The checksum database makes content tampering and per-user substitution detectable; whether the published code is safe still needs review and govulncheck.","objective":"Run govulncheck in CI, rely on go.sum and the checksum database correctly, pin tools with tool directives, build with -trimpath, and audit a binary's embedded build information.","question":"A new version of a dependency is listed in the Go checksum database. What does that establish?","references":["https://go.dev/doc/security/vuln/","https://pkg.go.dev/golang.org/x/vuln/cmd/govulncheck","https://go.dev/ref/mod#authenticating","https://pkg.go.dev/runtime/debug#ReadBuildInfo"],"reviewAnswer":"Everyone gets the same content for a module version","reviewPrompt":"What does sum.golang.org prove?","sections":[{"body":"govulncheck compares your dependencies, and the Go version itself, against the Go vulnerability database. In source mode it builds a call graph and reports a vulnerability as affecting you only when your code can reach a vulnerable function, which turns a long list of advisories into the few that matter now. Vulnerable modules that you import but never call are summarized separately. Binary mode inspects a compiled executable, which is the right check for what you actually ship, but it cannot show call stacks. Standard-library vulnerabilities are fixed by moving to a newer Go patch release, so scan with the same Go version you release with.","code":"# Pin the scanner in go.mod (Go 1.24+), so developers and CI run one version:\ngo get -tool golang.org/x/vuln/cmd/govulncheck@latest\n\ngo tool govulncheck ./...                       # source mode: reachable findings\ngo tool govulncheck -show verbose ./...         # also list imported but unreached ones\ngo tool govulncheck -mode=binary ./bin/orders   # audit what you actually ship","language":"bash","title":"Report the vulnerabilities your code can reach","walkthrough":"Run these in your own module; govulncheck fetches advisories from the Go vulnerability database. go get -tool records the resolved version in go.mod and go.sum, and go tool runs exactly that version, building it on first use. In its default text output, govulncheck exits with a non-zero status when it finds vulnerabilities your code reaches, so a CI step fails on the findings that matter. Reachability is a static approximation: reflection and some indirect calls can hide a path, so schedule upgrades for unreached findings instead of ignoring them."},{"body":"go.sum records a hash of each module version's file tree and of its go.mod file. When the go command first downloads a module version that go.sum does not list, it checks the hash against sum.golang.org, a transparent log that lets every user confirm they see the same content for the same version. That defends against a compromised proxy or origin serving you different code from everyone else, and against a version tag moved after publication. It does not say the code is benign: a malicious version published openly is logged faithfully. Private modules must not be looked up in public services, which is what GOPRIVATE controls.","code":"go env -w GOPRIVATE='*.corp.example.com'   # no public proxy or checksum DB for these\ngo mod verify                               # module cache still matches go.sum\ngo mod tidy -diff                           # non-zero exit if go.mod or go.sum would change\ngo build -mod=readonly -trimpath -o bin/orders ./cmd/orders\ngo version -m bin/orders                    # the embedded module and build record","language":"bash","title":"What go.sum and the checksum database prove","walkthrough":"Run these in your own environment. GOPRIVATE takes comma-separated glob patterns of module path prefixes and keeps those modules away from proxy.golang.org and sum.golang.org; GONOPROXY and GONOSUMDB override it for finer control. go mod verify detects tampering in the local module cache. go mod tidy -diff prints needed changes and exits non-zero, so CI catches a go.mod that drifted from the imports. -mod=readonly is already the default without a vendor directory, but stating it guards against a GOFLAGS=-mod=mod in the environment quietly rewriting requirements. -trimpath replaces file system paths with module paths, so binaries do not reveal the build machine's layout and are easier to reproduce."},{"body":"Tools that run in CI or through go generate, such as linters, code generators and govulncheck, execute with your repository's credentials, so they deserve the same pinning as libraries. Since Go 1.24 a tool directive in go.mod records each one: go tool runs it at the recorded version, go get tool upgrades every declared tool, and go install tool installs them into GOBIN. Tool dependencies join your module graph, which can raise shared dependency versions for the application too; if that is unwanted, declare the tools in a separate go.mod and pass -modfile to go tool. Avoid go install pkg@latest and download-and-run installers in CI scripts: they execute whatever was published most recently, unreviewed.","title":"Pin and review tools like code"},{"body":"Every module-mode binary embeds its main module, its dependency versions with checksums, and build settings such as -trimpath, CGO_ENABLED and the VCS revision. go version -m prints that record, debug/buildinfo.ReadFile reads it from a file, and runtime/debug.ReadBuildInfo returns the running program's own copy. A release gate can read the candidate binary and refuse to ship it when the record shows a modified working tree or a dependency replaced by a local directory. The program applies such a policy to a fixed record and then prints only those fields of its own record that do not vary between environments.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\t\"runtime/debug\"\n)\n\n// candidate is what debug/buildinfo.ReadFile returns for a release binary;\n// `go version -m ./orders` prints the same record as text.\nvar candidate = &debug.BuildInfo{\n\tPath: \"example.com/orders/cmd/orders\",\n\tMain: debug.Module{Path: \"example.com/orders\", Version: \"v1.8.0+dirty\"},\n\tDeps: []*debug.Module{\n\t\t{Path: \"example.com/auth\", Version: \"v0.3.1\",\n\t\t\tReplace: &debug.Module{Path: \"../auth\", Version: \"(devel)\"}},\n\t\t{Path: \"golang.org/x/crypto\", Version: \"v0.57.0\", Sum: \"h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=\"},\n\t\t{Path: \"golang.org/x/sys\", Version: \"v0.48.0\", Sum: \"h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=\"},\n\t},\n\tSettings: []debug.BuildSetting{\n\t\t{Key: \"-compiler\", Value: \"gc\"},\n\t\t{Key: \"-trimpath\", Value: \"true\"},\n\t\t{Key: \"CGO_ENABLED\", Value: \"0\"},\n\t\t{Key: \"GOOS\", Value: \"linux\"},\n\t\t{Key: \"vcs\", Value: \"git\"},\n\t\t{Key: \"vcs.revision\", Value: \"4b825dc642cb6eb9a060e54bf8d69288fbee4904\"},\n\t\t{Key: \"vcs.modified\", Value: \"true\"},\n\t},\n}\n\n// audit applies a release policy to embedded build information.\nfunc audit(bi *debug.BuildInfo) []string {\n\tsettings := map[string]string{}\n\tfor _, s := range bi.Settings {\n\t\tsettings[s.Key] = s.Value\n\t}\n\tvar problems []string\n\tif settings[\"-trimpath\"] != \"true\" {\n\t\tproblems = append(problems, \"built without -trimpath\")\n\t}\n\tif settings[\"vcs.revision\"] == \"\" {\n\t\tproblems = append(problems, \"no VCS revision stamped\")\n\t}\n\tif settings[\"vcs.modified\"] != \"false\" {\n\t\tproblems = append(problems, \"built from a modified working tree\")\n\t}\n\tfor _, d := range bi.Deps { // a slice, so findings keep a stable order\n\t\tswitch {\n\t\tcase d.Replace != nil && d.Replace.Sum == \"\":\n\t\t\tproblems = append(problems, d.Path+\" replaced by local directory \"+d.Replace.Path)\n\t\tcase d.Replace == nil && d.Sum == \"\":\n\t\t\tproblems = append(problems, d.Path+\" has no checksum\")\n\t\t}\n\t}\n\treturn problems\n}\n\nfunc main() {\n\tfmt.Println(\"candidate:\", candidate.Main.Path, candidate.Main.Version, \"deps:\", len(candidate.Deps))\n\tproblems := audit(candidate)\n\tfor _, p := range problems {\n\t\tfmt.Println(\"block:\", p)\n\t}\n\tfmt.Println(\"release allowed:\", len(problems) == 0)\n\n\tself, ok := debug.ReadBuildInfo() // the record embedded in this very program\n\tfmt.Println(\"self has build info:\", ok)\n\tif ok {\n\t\tfmt.Println(\"self GoVersion == runtime.Version():\", self.GoVersion == runtime.Version())\n\t\tfmt.Println(\"self dependency modules:\", len(self.Deps))\n\t}\n}","language":"go","title":"Audit what a binary was built from","walkthrough":"candidate mirrors what the go command records for a build from a modified checkout: since Go 1.24, go build appends +dirty to the main module version and sets vcs.modified=true. The replaced dependency carries no checksum because a directory has no published content to hash, which is exactly why it must not reach a release. audit walks Settings and Deps as slices, so findings print in a stable order. For the running program, ReadBuildInfo fills GoVersion from runtime.Version, and a program that imports only the standard library lists no dependency modules. Paths, VCS fields and target platform vary by environment, so they are not printed; go run does not stamp VCS information at all, while go build does."},{"body":"Each upgrade imports code that runs with your service's privileges. Update deliberately, one dependency or one related group per change, so a regression points at its cause. Read the go.mod and go.sum diff and look for modules that arrived transitively; go mod why -m explains why a module is needed and go mod graph shows who requires it. Skim the release notes and the size of the source diff in the upstream repository. Run the tests and govulncheck on the result. Automated update pull requests, such as Dependabot version updates for Go modules, are useful when a person reviews them with the same care as any other change. And prefer fewer dependencies: a small, well-understood helper is sometimes cheaper to own than a module that brings twenty more.","code":"go list -m -u all                    # available upgrades appear in [brackets]\ngo get golang.org/x/net@v0.61.0 && go mod tidy\ngit diff go.mod go.sum               # new transitive modules show up here\ngo mod why -m golang.org/x/text      # which import path needs this module\ngo test ./... && go tool govulncheck ./...","language":"bash","title":"Review dependency updates as code changes","walkthrough":"Run these in your own module; the module and version are examples. go list -m -u all shows each module with any newer version in brackets. go get changes one requirement and go mod tidy settles the graph, after which the git diff of go.mod and go.sum is the review surface: every new line in go.sum is code you have not seen before. go mod why -m prints the shortest import path that needs the module. The last line gates the change on tests and reachable vulnerabilities, the same checks CI repeats."}],"takeaway":"Keep the toolchain's defaults on (go.sum, the checksum database, read-only module mode), gate CI on reachable govulncheck findings, pin tools in go.mod, and refuse releases whose embedded build information shows a dirty tree or a local replacement.","title":"Secure the Go supply chain: reachable vulnerabilities, verified modules, pinned tools, auditable binaries","unitID":"security-operations","wrongAnswers":["The version was reviewed and contains no malware","The version has no known vulnerabilities"]}],"revision":"2026-11-18.1","schemaVersion":1,"solutions":{},"units":[{"id":"security","lessons":[{"conceptTags":["security.identity-authorization"],"explanation":"A signed token can be genuine and still belong to the wrong audience, issuer or operation. Even a fully valid token does not prove that its subject may read a particular order. Treat authentication as construction of a verified principal and authorization as an explicit resource-scoped decision. Fail closed when either contract is missing rather than accepting whatever identity-shaped value a request provides.","id":"security.identity-authorization","objective":"Validate identity separately from permission to act on a particular resource.","task":{"reading":{}},"title":"Authentication and authorization: a verified token is only the beginning"},{"conceptTags":["security.crypto-purposes"],"explanation":"A fast hash, password hash, MAC, encryption scheme and digital signature answer different questions. A SHA-256 digest does not make a password database resistant to guessing, and encryption without authentication can accept altered ciphertext. Use reviewed libraries and document the purpose, key lifetime, input format and resource budget before selecting a primitive.","id":"security.crypto-purposes","objective":"Choose purpose-specific primitives and bound their cost instead of inventing cryptography.","task":{"reading":{}},"title":"Passwords, MACs and randomness solve different problems"},{"conceptTags":["security.ssrf-egress"],"explanation":"A URL supplied by a user can target internal services, metadata endpoints or a different host after redirection. Checking that the string begins with https is insufficient. Prefer a small configured set of upstream services and let user input select a resource within one of them. When arbitrary destinations are a real requirement, enforce address and egress policy at connection time as well as during URL parsing.","id":"security.ssrf-egress","objective":"Keep outbound destinations controlled and validate redirects and connection-time policy.","task":{"reading":{}},"title":"SSRF: let user input choose data, not an arbitrary network destination"},{"conceptTags":["security.tls-trust"],"explanation":"A TLS connection can encrypt traffic to the wrong peer if verification is disabled. Certificate chain trust and hostname identity both matter; changing a boolean until a development request succeeds can silently remove production authentication. Use a deliberate trust store, keep the expected server identity tied to the configured destination and handle private development certificates through a separate test trust configuration.","id":"security.tls-trust","objective":"Keep certificate-chain and hostname verification while making trust and rotation explicit.","task":{"reading":{}},"title":"TLS: verify the peer instead of disabling the error"}],"summary":"Authentication and authorization, cryptographic purposes, controlled egress and TLS peer identity.","title":"Service security foundations","translationNote":"Apply these patterns in your own native services with an explicit threat model. These lessons do not introduce GopherForge accounts or registration."},{"id":"security-web","lessons":[{"conceptTags":["security.sql-injection"],"explanation":"SQL injection happens when a value supplied by a user becomes part of the statement the database parses. database/sql gives you a second channel: the query text reaches the driver as one string and every argument travels beside it as a typed value. The SQL rows lesson stated that placeholders bind values, not grammar; this lesson makes that separation visible with a recording driver and covers the places where binding alone is not enough: identifiers, sort direction and LIKE patterns.","id":"security.sql-injection","objective":"Send untrusted values as database/sql arguments, pick identifiers from allow-lists in code and escape LIKE wildcards with an explicit ESCAPE clause.","task":{"reading":{}},"title":"SQL injection: the query text and the user's values must reach the driver separately"},{"conceptTags":["security.xss-templates"],"explanation":"Cross-site scripting happens when data from one user becomes markup or script in another user's browser. Escaping is the defense, but the correct escaping depends on where a value lands: a text node, a quoted attribute, a URL, a JavaScript string and a CSS value each have different metacharacters. Go's html/template parses your template, tracks that context at every action and applies the matching escaper automatically. text/template does none of this, and typed strings such as template.HTML tell html/template to stop.","id":"security.xss-templates","objective":"Render untrusted data with html/template, read its context-specific escaping and treat every typed-content conversion as a reviewed trust decision.","task":{"reading":{}},"title":"html/template escapes by context, and template.HTML is where that protection switches off"},{"conceptTags":["security.csrf-protection"],"explanation":"Cross-site request forgery abuses ambient credentials. A page on another site submits a form or calls fetch toward your service, the browser attaches your session cookie, and your handler sees an authenticated request it never meant to accept. Since Go 1.25 the standard library ships http.CrossOriginProtection, which rejects non-safe cross-origin browser requests using the Sec-Fetch-Site and Origin headers instead of a per-form secret. This lesson shows what that check decides, where SameSite fits and what stays your responsibility.","id":"security.csrf-protection","objective":"Protect cookie-authenticated endpoints with net/http's CrossOriginProtection, know what SameSite cookies add and recognize when a synchronizer token is still required.","task":{"reading":{}},"title":"CSRF: reject cross-origin writes with Sec-Fetch-Site and http.CrossOriginProtection"},{"conceptTags":["security.session-cookies"],"explanation":"A session cookie is a bearer credential: whoever presents it is the user until the server decides otherwise. Its attributes control where the browser sends it and whether page scripts can read it; the server-side record controls how long it is honored. Getting either half wrong produces familiar incidents: a cookie copied out by an injected script, a session an attacker fixed before the victim logged in, or a logout that only deleted the browser's copy.","id":"security.session-cookies","objective":"Issue a __Host- session cookie with the right attributes, rotate the ID at login and enforce idle, absolute and logout expiry in a server-side store.","task":{"reading":{}},"title":"Session cookies: lock down the attributes and keep the session's lifetime on the server"},{"conceptTags":["security.path-traversal"],"explanation":"Path traversal turns a file name from a request into access somewhere else on disk: ../ segments, an absolute path or a symlink that leads out of the intended directory. The classic Go defense, filepath.Join plus Clean plus a prefix check, works on strings while the kernel resolves the real path later, symlinks included. Go 1.24 added os.Root, which opens a directory once and resolves every later name inside it, and Go 1.25 extended it with ReadFile, WriteFile, MkdirAll and other helpers.","id":"security.path-traversal","objective":"Open user-named files through os.Root, use filepath.IsLocal and Localize for early rejection and extract archives without zip-slip.","task":{"reading":{}},"title":"Path traversal: confine file access with os.Root, because Join and Clean only edit strings"},{"conceptTags":["security.command-injection"],"explanation":"Go's os/exec does not invoke a shell: exec.Command takes a program and an argument slice, so semicolons and $(...) inside an argument are ordinary bytes. The operations lessons on Bash arguments and safe CLIs already rely on that. This lesson covers the injection that survives without a shell: a user value read as an option by the target program, an operation chosen by the request, and a child process that inherits your environment and outlives its deadline.","id":"security.command-injection","objective":"Start external tools with exec.CommandContext and a fixed argv, block argument injection with validation and --, and bound the child's time and environment.","task":{"reading":{}},"title":"Command injection: run tools without a shell and keep user input out of option position"},{"conceptTags":["security.open-redirects"],"explanation":"Login, logout and OAuth flows often carry a next or return_to parameter. If the server redirects to whatever it contains, an attacker can send a link that starts on your trusted domain and ends on a lookalike login page, and in OAuth flows a redirect can leak codes or tokens. The obvious fix, allow only relative paths, is harder than it looks: browsers parse URLs by the WHATWG URL Standard, Go's net/url follows RFC 3986, and every difference between them is a bypass.","id":"security.open-redirects","objective":"Validate redirect targets so only same-site paths and allow-listed https URLs pass, including the //host, backslash and userinfo tricks that browsers and net/url read differently.","task":{"reading":{}},"title":"Open redirects: accept a single-slash path or an allow-listed host, not any URL that parses"},{"conceptTags":["security.http-headers"],"explanation":"Response headers turn browser features into policy: which scripts may run, whether the page may be framed, whether a response may be reinterpreted as another content type, how much of the URL leaks to other sites and whether plain HTTP is ever acceptable again. None of them fixes a bug in your handlers. They limit what an escaping mistake, an injected script or a hostile frame can do, so they belong in one middleware that wraps every response.","id":"security.http-headers","objective":"Write middleware that sets a nonce-based Content-Security-Policy and the other baseline security headers, and roll them out without breaking pages or locking in HSTS preload by accident.","task":{"reading":{}},"title":"Security headers: a per-request CSP nonce, HSTS, nosniff, frame-ancestors and Referrer-Policy"}],"summary":"SQL injection, XSS, CSRF, session cookies, path traversal, command injection, open redirects and security headers.","title":"Web application security","translationNote":"Each attack is shown against a local model and fixed with the standard library. Test only systems you own or are authorized to assess."},{"id":"security-operations","lessons":[{"conceptTags":["security.secrets-redaction"],"explanation":"Most leaked credentials are not stolen from a vault; they are printed. A startup line that logs the configuration with %+v, an error that wraps a connection string, a debug endpoint that dumps settings: each copies the secret into log storage that more people can read, for longer, than the secret store itself. Make printing safe by default and make revealing the value an explicit, searchable call.","id":"security.secrets-redaction","objective":"Wrap credentials in a Secret type that redacts itself in fmt, slog and JSON, redact credentials in URLs, and load secrets with errors that name the source but never the value.","task":{"reading":{}},"title":"Keep secrets out of logs and errors with a type that refuses to print itself"},{"conceptTags":["security.constant-time"],"explanation":"A comparison that stops at the first differing byte takes longer the more of the guess is correct. Against a token, an API key or a MAC tag, that turns an impossible search over the whole value into a byte-by-byte search an attacker can run with enough repeated requests. Constant time here means time that depends only on public facts, such as the length, and never on the contents of the secret.","id":"security.constant-time","objective":"Recognize timing-dependent comparisons and replace them with crypto/subtle or hmac.Equal over fixed-size digests, including the lookup and error paths around them.","task":{"reading":{}},"title":"Compare secrets in constant time: an early return reveals how much of a guess was right"},{"conceptTags":["security.aead-encryption"],"explanation":"Encrypting a column protects data in backups, replicas and database dumps, but only if the record format answers more than which key to use. The crypto-purposes lesson explains why encryption must be authenticated. This lesson builds the record envelope: AES-GCM through crypto/cipher, a fresh random nonce per seal, a key ID that survives rotation, and additional data that ties each ciphertext to the row it belongs to.","id":"security.aead-encryption","objective":"Seal application records with AES-GCM so that tampering, row swapping and key rotation are handled explicitly, and explain why a repeated nonce breaks GCM.","task":{"reading":{}},"title":"Encrypt records with AES-GCM: random nonces, a key ID, and the record ID as additional data"},{"conceptTags":["security.password-storage"],"explanation":"The crypto-purposes lesson establishes that passwords need a slow, salted, memory-hard function. The operational questions come next: how to store the parameters with each hash so they can change later, how to upgrade old hashes without forcing resets, how to budget memory when many users log in at once, and how to keep the login endpoint from telling an attacker which accounts exist.","id":"security.password-storage","objective":"Hash passwords with argon2id in a self-describing PHC-style string, upgrade parameters at login, handle bcrypt's 72-byte limit and keep login failures indistinguishable.","task":{"reading":{}},"title":"Store passwords with argon2id: encoded parameters, rehash on login, one answer for every failure"},{"conceptTags":["security.token-design"],"explanation":"The identity-authorization lesson says to validate a token's full contract before trusting the principal it names. This lesson designs the tokens themselves. Opaque tokens are random strings that mean nothing without a lookup, so revocation is immediate. Signed tokens carry their claims and verify without a lookup, so revocation is hard and every claim check is your job. Both need expiry, rotation and a plan for theft.","id":"security.token-design","objective":"Choose between opaque and signed tokens, store opaque tokens as hashes with rotation and reuse detection, and verify HMAC-signed JWTs with a pinned algorithm and checked claims.","task":{"reading":{}},"title":"Design tokens deliberately: hashed opaque tokens, strictly verified signed tokens, expiry and rotation"},{"conceptTags":["security.fuzzing-parsers"],"explanation":"Every parser that reads bytes from outside the process is attack surface: upload formats, binary protocols, compressed bodies, custom headers. Unit tests check the inputs you thought of. Go's built-in fuzzer mutates seed inputs, guided by coverage, to find the ones you did not, such as a length field that points past the end or a non-canonical encoding that breaks a round trip.","id":"security.fuzzing-parsers","objective":"Write a native Go fuzz test with seed inputs and real invariants for a binary parser, harden the parser against what it finds, and cap decompressed size with io.LimitReader.","task":{"reading":{}},"title":"Fuzz the parsers that read untrusted bytes, and bound what they may allocate or inflate"},{"conceptTags":["security.supply-chain"],"explanation":"Most of the code in a Go binary was written by someone else. The toolchain provides strong defaults: go.sum pins exact module content, the checksum database exposes a module version that changed after publication, and every binary records the modules it was built from. Supply-chain security in Go is mostly about not weakening those defaults, and about reacting quickly and precisely when a dependency has a known vulnerability.","id":"security.supply-chain","objective":"Run govulncheck in CI, rely on go.sum and the checksum database correctly, pin tools with tool directives, build with -trimpath, and audit a binary's embedded build information.","task":{"reading":{}},"title":"Secure the Go supply chain: reachable vulnerabilities, verified modules, pinned tools, auditable binaries"}],"summary":"Redaction, constant-time checks, AEAD encryption, password storage, token design, fuzzing and dependency hygiene.","title":"Secrets, cryptography and supply chain","translationNote":"Use reviewed standard and x/crypto primitives rather than inventing constructions. Production key storage and rotation need your own infrastructure."}]}