Nil Context

ID

go.nil_context

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Go

Tags

reliability, suspicious

Description

Reports a literal nil passed where a context.Context is expected: the context.WithCancel / context.WithValue / context.WithDeadline / context.WithTimeout family (the parent context) and http.NewRequestWithContext (the request context).

Rationale

The context package documentation states that a nil Context must never be passed; code that is unsure which context to use should pass context.TODO(). A nil parent panics inside the derivation helpers, and a nil request context silently disables cancellation and deadline propagation, so requests cannot be aborted and resources may leak.

context.WithCancel(nil)                          // FLAW
http.NewRequestWithContext(nil, "GET", "/", nil) // FLAW

ctx := context.Background()
context.WithCancel(ctx)                          // OK — real parent context

Remediation

Pass a real context — typically the one received from the caller. At the top of a call chain use context.Background(); use context.TODO() as a placeholder when the right context is not yet plumbed through.