golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
123.24k stars 17.57k forks source link

context: panic when creating an invalid context #37908

Closed knusbaum closed 4 years ago

knusbaum commented 4 years ago

What version of Go are you using (go version)?

$ go version
go version go1.14 darwin/amd64

Does this issue reproduce with the latest release?

Yes

What operating system and processor architecture are you using (go env)?

go env Output
$ go env
GO111MODULE=""
GOARCH="amd64"
GOBIN=""
GOCACHE="/Users/kyle.nusbaum/Library/Caches/go-build"
GOENV="/Users/kyle.nusbaum/Library/Application Support/go/env"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOINSECURE=""
GONOPROXY=""
GONOSUMDB=""
GOOS="darwin"
GOPATH="/Users/kyle.nusbaum/Documents/CodeBase/gotree"
GOPRIVATE=""
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/usr/local/Cellar/go/1.14/libexec"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/usr/local/Cellar/go/1.14/libexec/pkg/tool/darwin_amd64"
GCCGO="gccgo"
AR="ar"
CC="clang"
CXX="clang++"
CGO_ENABLED="1"
GOMOD="/Users/kyle.nusbaum/Documents/CodeBase/go/src/go.mod"
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=/var/folders/8x/bn6z9tk109n_hvbhl8fwdmpw0000gn/T/go-build192830994=/tmp/go-build -gno-record-gcc-switches -fno-common"

What did you do?

It's possible to create an invalid Context that can propagate through the program and later cause a nil dereference panic when Value is called: https://play.golang.org/p/zJMpPmKL5M7

One of the trickier things about this is that the context will work as expected until you try to look up a Value that isn't in the context: https://play.golang.org/p/aLyNCZTeWN8

Because of this and the nature of the Context as a carrier of data, etc. across API boundaries, the source of the bad context and the place where the panic occurs are often in entirely unrelated pieces of code, making tracking down the bug difficult.

What did you expect to see?

WithValue should panic when passed a nil parent context.

What did you see instead?

WithValue returns a Context that can later cause a panic.

gopherbot commented 4 years ago

Change https://golang.org/cl/223777 mentions this issue: context: prevent creation of invalid contexts