For senior developers

Securing a Go API against the OWASP Top 10

The OWASP list is not a vulnerability catalogue, it is a ranking of what actually goes wrong, drawn from real applications. Read that way it is useful: it tells you where to spend an afternoon rather than giving you a list to tick.

Each section below names the risk, shows what it looks like in a Go API, gives the fix as code, and ends with something you can automate, because a security property nobody checks is a security property that decays.

24 min read. Commands and output last run against Grit v3.560.0.

What you will have at the end

A specific change for each risk, in Go, rather than a principle to bear in mind.

A short list of checks that run in CI, so this does not have to be remembered.

An honest sense of which of the ten are already handled by Go and which are not.

The two that account for most real incidents

If you only have an afternoon: broken access control and vulnerable dependencies. The first is the most common finding in web applications by a wide margin, and the second is the one that arrives without you writing any code at all.

1. Broken access control

The largest category, and in a Go API it is almost always the same shape: a handler that loads a record by id without asking whose it is.

// Wrong. The route is behind auth, the user has the permission, and
// any id they type returns somebody's invoice.
db.First(&invoice, c.Param("id"))
// Right: the scope is part of the query, so an out-of-scope row cannot
// be returned at all, and forgetting the argument does not compile.
db.Where("id = ? AND organisation_id = ?", c.Param("id"), orgID).First(&invoice)
  • Answer 404 for a row outside the caller's scope, not 403. A 403 confirms the record exists, which is half of what an attacker wanted.
  • Check every way into a table. Bulk edit, export, import, search and background jobs are each a separate path, and one of them written without the scope undoes the others.
  • Deny by default. A new route should be unreachable until something grants access, rather than open until somebody remembers to guard it.

Automate it: a static route table listing which middleware guards what, and a test per resource that attempts access as the wrong tenant and expects 404. Make that test fail once on purpose; an isolation test passes for the wrong reason more easily than most.

The full treatment is in the authorization guide.

2. Cryptographic failures

Go's standard library is good here, so most failures are misuse rather than weakness.

// Passwords: a deliberately slow hash, never a fast one. SHA-256 on a
// password is a password, lightly inconvenienced.
hash, err := bcrypt.GenerateFromPassword([]byte(plain), 12)
// Tokens and secrets: crypto/rand, never math/rand. math/rand is
// predictable by design and is for simulations.
buf := make([]byte, 32)
if _, err := rand.Read(buf); err != nil { // crypto/rand
return fmt.Errorf("generate token: %w", err)
}
// Comparing secrets: constant time, so the comparison does not leak how
// much of the value was correct.
if subtle.ConstantTimeCompare([]byte(given), []byte(expected)) != 1 {
return ErrInvalid
}
  • Store a hash of a token, not the token. SHA-256 is right here, because the input is already high-entropy and the lookup must be fast. bcrypt is for low-entropy human passwords.
  • TLS everywhere, including internally. "It is on a private network" is an assumption about a network you do not control.
  • Secrets from the environment, and the process refuses to start without them. A default that is used when a variable is missing will one day be used in production.

Automate it: a secret scanner on every commit and in CI. A credential in git history is not removed by deleting it from the current file, and a public repository is scraped within minutes.

3. Injection

Mostly solved for you in Go, with specific exceptions that are worth knowing precisely.

// Safe. GORM parameterises, so the value is never parsed as SQL.
db.Where("email = ?", userInput).First(&user)
// Not safe: an identifier cannot be a parameter, so people concatenate.
db.Order(userSortColumn + " " + userDirection)
db.Raw("SELECT * FROM " + tableName)
// Safe: an allow-list, because the set of valid identifiers is small
// and known.
var sortable = map[string]bool{"created_at": true, "total": true, "status": true}
if !sortable[col] {
col = "created_at"
}
db.Clauses(clause.OrderBy{Columns: []clause.OrderByColumn{{
Column: clause.Column{Name: col}, Desc: desc,
}}})

Three injection surfaces that are not SQL and are easy to miss:

  • Command injection. exec.Command with arguments is safe because Go does not use a shell. exec.Command("sh", "-c", userInput) reintroduces the shell and every problem with it.
  • Template injection. html/template escapes by context and is safe. text/template does not escape at all, and using it to produce HTML is a cross-site scripting hole with no warning.
  • Path traversal. A filename from a request, joined to a directory, reaches anywhere with enough ../. Never build a path from user input; generate the key yourself and keep the original name in a column.

Automate it: gosec in CI catches string-built SQL, text/template for HTML and unsafe path joins. Run it per directory rather than over the whole module: its loader chunks the file list and a large package can produce "undefined" errors on code that builds perfectly.

4. Insecure design

The category that cannot be fixed by a library, because it is about what the system permits rather than how it is written. In a typical API it shows up as missing limits.

  • Rate limits on anything that costs something: login, password reset, email sending, export, anything calling a paid API. Per account as well as per IP, because a distributed attempt on one account spreads across addresses.
  • A maximum on every pagination parameter. A caller-controlled page_size with no ceiling decides how much memory you allocate.
  • A maximum request body size, set globally rather than per handler.
  • Workflow states that cannot be skipped. If an invoice must be sent before it is paid, the service enforces that, not the interface.
  • Quotas per tenant, so one customer cannot exhaust a shared resource.
r.Use(func(c *gin.Context) {
// Before any handler reads it. The default is unlimited.
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 10<<20)
c.Next()
})

5. Security misconfiguration

// Timeouts, because the defaults are "wait forever". Without
// ReadHeaderTimeout, a client that opens a connection and sends headers
// one byte at a time holds it indefinitely, for free.
srv := &http.Server{
Addr: cfg.Addr,
Handler: r,
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 15 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 60 * time.Second,
MaxHeaderBytes: 1 << 20,
}
  • gin.SetMode(gin.ReleaseMode) in production. Debug mode prints routes and verbose errors.
  • Security headers: HSTS, X-Content-Type-Options: nosniff, X-Frame-Options: DENY, a referrer policy, and a content security policy if you serve HTML.
  • CORS that names origins. A wildcard plus credentials is refused by browsers anyway, so a wildcard is a sign the design has not met authentication yet.
  • No stack traces in responses. Log the real error with a request id; return a code and a sentence.
  • Nothing but your application on the public interface. Databases, caches and admin panels reachable only through a tunnel.

6. Vulnerable and outdated components

The risk that arrives without you writing anything. Go has unusually good tooling for it, and the reachability analysis is the part that makes it usable.

Terminal
$govulncheck ./...

It reports only vulnerabilities your code can actually reach, through static analysis of the call graph, rather than every advisory touching anything in your dependency tree. That difference is what stops the output being ignored.

The Go toolchain is a dependency too

A large share of Go advisories are in the standard library: net/http, crypto/tls, encoding/xml. Pinning your modules and building with a two-year-old Go leaves them all. The go directive in go.mod is as much a security decision as any module version.

Automate it: govulncheck in CI on every pull request, and again on a nightly schedule. Nightly matters because an advisory published after your last commit will never be seen by a per-commit run.

7. Identification and authentication failures

Four defences, each catching something the others do not.

  • Per-IP and per-account rate limiting on sign-in.
  • Temporary lockout after repeated failures, with an increasing delay.
  • Identical answers for every failure. Unknown account, wrong password and locked account must be indistinguishable, including a locked account: otherwise the lockout message becomes the account-existence oracle the identical messages were there to close.
  • Identical timing. Hash a dummy password when the account does not exist, so a missing user does not return in two milliseconds while a wrong password takes three hundred.
user, err := s.repo.ByEmail(ctx, email)
if err != nil {
// Spend the time we would have spent verifying, so the two paths
// cannot be told apart with a stopwatch.
bcrypt.CompareHashAndPassword(dummyHash, []byte(password))
return nil, ErrInvalidCredentials
}
if !CheckPassword(user.PasswordHash, password) {
return nil, ErrInvalidCredentials
}

On sessions: rotate the refresh token on every use and treat the reuse of an already-used one as theft, revoking the whole family. Keep refresh tokens in HttpOnly cookies rather than localStorage, where any script on the page can read them.

8. Software and data integrity failures

  • Verify webhook signatures, with a constant-time compare and a timestamp tolerance, and store the event id so a redelivery is ignored rather than processed twice. An unverified webhook endpoint is an unauthenticated write endpoint.
  • Never deserialise into a model. Bind to a request struct, which is an allow-list by construction. Binding into a GORM model lets a caller set role or organisation_id.
  • Pin CI actions by commit SHA, not by a tag. A tag can be moved to point at different code.
  • Commit go.sum and do not bypass verification. It is what stops a dependency being swapped under you.

9. Logging and monitoring failures

The failure here is not an attack, it is not noticing one. The median time to detect a breach is measured in months, and the usual reason is that nothing was recorded.

// Log the security-relevant events specifically, structured, with a
// request id that ties them to everything else from the same request.
log.Info().
Str("event", "auth.login.failed").
Str("email", redact(email)). // not the raw address in plain logs
Str("ip", c.ClientIP()).
Str("request_id", respond.RequestID(c)).
Msg("sign-in failed")
  • Record: sign-in success and failure, password and email changes, permission denials, role changes, exports, and administrative actions.
  • Never record: passwords, tokens, session identifiers, card details, or whole request bodies on authentication routes.
  • Alert on patterns, not events. One failed sign-in is noise. Forty from one address in a minute, or one account failing from twelve countries, is a signal.
  • An append-only audit log for the actions that matter, separate from application logs, which are rotated and are not evidence.

10. Server-side request forgery

Any feature that fetches a URL supplied by a user, an avatar from a link, a webhook target, a website preview, can be pointed at your own infrastructure, including cloud metadata endpoints that hand out credentials.

// Resolve first and check the address, because a hostname can resolve
// to a private address and a redirect can change it mid-flight.
func safeDial(ctx context.Context, network, addr string) (net.Conn, error) {
host, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
ips, err := net.DefaultResolver.LookupIPAddr(ctx, host)
if err != nil {
return nil, err
}
for _, ip := range ips {
if ip.IP.IsLoopback() || ip.IP.IsPrivate() ||
ip.IP.IsLinkLocalUnicast() || ip.IP.IsUnspecified() {
return nil, fmt.Errorf("refusing to connect to %s", ip.IP)
}
}
return (&net.Dialer{Timeout: 5 * time.Second}).DialContext(ctx, network, addr)
}
client := &http.Client{
Transport: &http.Transport{DialContext: safeDial},
Timeout: 10 * time.Second,
// Redirects are checked too: without this, a public URL can redirect
// to 169.254.169.254 and the check above never sees it.
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) >= 3 {
return errors.New("too many redirects")
}
return nil
},
}

Checking the hostname before resolving is the common mistake, because a name you allow can resolve to an address you do not. Check the address, on every hop.

What to put in CI

The point of this section: everything above decays unless something checks it after you have stopped thinking about it.

.github/workflows/security.yml
- run: go vet ./...
- run: govulncheck ./... # reachable CVEs, including stdlib
- run: gosec ./... # per directory on a large module
- run: go test -race ./... # a data race is a security bug
- run: gitleaks detect # secrets, including in history
# Nightly as well as per-commit: an advisory published after your last
# commit is never seen by a per-commit run.

What is already true in a generated project

Most of the list is a default rather than an exercise: parameterised queries, bcrypt at a sensible cost, refresh rotation with replay detection, identical answers and identical timing on sign-in, security headers, server timeouts, a body size limit, CORS from configuration, rate limits on the authentication routes, and structured logs with a request id.

Terminal
$grit doctor # offline checks against the project's own files
$grit add scout # a scanner, fed the generated route table

grit doctor reads files and compiled-in floors and never the network, which is what makes it usable in CI. It reports the specific faults this page describes: an unguarded route, a tenant table without the scope, a missing index on a tenant column, a Go toolchain below the floor.

The security reference covers the defaults and what each one is protecting against.

Frequently asked questions

Which of these does Go handle for me?
Memory safety, so the buffer overflow category is gone. SQL injection, as long as you use parameters and never concatenate. Cross-site scripting, if you use html/template rather than text/template. Everything else is application design, and access control, the largest category, has no language-level defence at all.
Is govulncheck enough for dependency scanning?
For Go code, it is the best available, because it reports what your call graph actually reaches rather than every advisory in the tree, which is the difference between output people read and output people mute. It does not cover your JavaScript dependencies or your container base image, so you need a second tool for those.
Do I need a WAF?
It is a second layer, not a first one. A WAF catches generic automated traffic and buys time when a vulnerability is disclosed before you can patch. It will not stop the request that looks entirely legitimate because the only thing wrong with it is that the id belongs to somebody else, which is the most common real vulnerability. Fix the application; add the WAF as well.
How often should any of this be reviewed?
The automated parts on every commit and nightly. The human parts when the shape changes: a new way into an existing table, a new integration that fetches a URL, a new role. Those are the moments a rule gets left behind, and they are easier to notice than a calendar reminder is to act on.

Next steps