How It Works Features Pricing Blog Error Guides
Log In Start Free Trial
Go · Go

Fix TLSHandshakeError: tls: failed to verify certificate: x509: certificate signed by unknown authority in Go

This error occurs when Go's HTTP client cannot verify the server's TLS certificate because it is self-signed, issued by an unknown CA, or the system's CA bundle is missing. Fix it by adding the CA certificate to the system trust store or configuring a custom TLS config with the CA certificate. Never disable TLS verification in production.

Reading the Stack Trace

goroutine 1 [running]: runtime/debug.Stack() /usr/local/go/src/runtime/debug/stack.go:24 +0x5e main.callInternalAPI() /app/client/internal.go:18 +0x2d8 crypto/tls.(*Conn).verifyServerCertificate(0x14000196040, {0x14000226060, 0x1, 0x1}) /usr/local/go/src/crypto/tls/handshake_client.go:963 +0x3e8 crypto/tls.(*clientHandshakeState).doFullHandshake(0x14000226000) /usr/local/go/src/crypto/tls/handshake_client.go:478 +0x484 crypto/tls.(*Conn).clientHandshake(0x14000196040, {0x1029f0ea0, 0x14000196060}) /usr/local/go/src/crypto/tls/handshake_client.go:161 +0x9c4 net/http.(*Transport).dialTLSHandshake(0x14000196040, {0x1029f0ea0, 0x14000196060}, {0x14000226060, 0x1}) /usr/local/go/src/net/http/transport.go:1604 +0x148

Here's what each line means:

Common Causes

1. Self-signed certificate on internal service

The target service uses a self-signed certificate that is not in the system's trusted CA store.

func callInternalAPI() (*Response, error) {
	resp, err := http.Get("https://internal-service:8443/api/data")
	if err != nil {
		return nil, err // TLS verification failure
	}
	defer resp.Body.Close()
	// ...
}

2. Minimal Docker image missing CA certificates

The Docker image (e.g., scratch or distroless) does not include system CA certificates.

FROM scratch
COPY app /app
CMD ["/app"]
# No CA certificates — all HTTPS requests fail

3. TLS verification disabled as a workaround

InsecureSkipVerify is set to true, disabling all certificate verification, which creates a security vulnerability.

client := &http.Client{
	Transport: &http.Transport{
		TLSClientConfig: &tls.Config{
			InsecureSkipVerify: true, // INSECURE — never do this in production
		},
	},
}

The Fix

Load the internal CA certificate from a PEM file and add it to a custom certificate pool. Configure the HTTP client's TLS settings with this pool. This validates the internal certificate properly without disabling security.

Before (broken)
func callInternalAPI() (*Response, error) {
	resp, err := http.Get("https://internal-service:8443/api/data")
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	var result Response
	json.NewDecoder(resp.Body).Decode(&result)
	return &result, nil
}
After (fixed)
func newInternalClient(caCertPath string) (*http.Client, error) {
	caCert, err := os.ReadFile(caCertPath)
	if err != nil {
		return nil, fmt.Errorf("reading CA cert: %w", err)
	}

	caPool := x509.NewCertPool()
	if !caPool.AppendCertsFromPEM(caCert) {
		return nil, fmt.Errorf("failed to parse CA certificate")
	}

	return &http.Client{
		Timeout: 10 * time.Second,
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{
				RootCAs: caPool,
			},
		},
	}, nil
}

func callInternalAPI(client *http.Client) (*Response, error) {
	resp, err := client.Get("https://internal-service:8443/api/data")
	if err != nil {
		return nil, fmt.Errorf("calling internal API: %w", err)
	}
	defer resp.Body.Close()

	var result Response
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		return nil, fmt.Errorf("decoding response: %w", err)
	}
	return &result, nil
}

Testing the Fix

package client_test

import (
	"crypto/tls"
	"crypto/x509"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestNewInternalClient_ValidCA(t *testing.T) {
	// Create a test server with TLS
	srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(`{"status": "ok"}`))
	}))
	defer srv.Close()

	// Use the test server's CA cert
	caPool := x509.NewCertPool()
	for _, cert := range srv.TLS.Certificates {
		for _, c := range cert.Certificate {
			parsed, _ := x509.ParseCertificate(c)
			caPool.AddCert(parsed)
		}
	}

	client := &http.Client{
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{RootCAs: caPool},
		},
	}

	resp, err := client.Get(srv.URL)
	assert.NoError(t, err)
	assert.Equal(t, http.StatusOK, resp.StatusCode)
}

func TestNewInternalClient_InvalidCAPath(t *testing.T) {
	_, err := newInternalClient("/nonexistent/ca.pem")
	assert.Error(t, err)
	assert.Contains(t, err.Error(), "reading CA cert")
}

Run your tests:

go test ./client/... -v

Pushing Through CI/CD

git checkout -b fix/go-tls-handshake-error,git add client/internal.go client/internal_test.go,git commit -m "fix: configure custom CA cert pool for internal service TLS",git push origin fix/go-tls-handshake-error

Your CI config should look something like this:

name: CI
on:
  pull_request:
    branches: [main]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-go@v5
        with:
          go-version: '1.22'
      - run: go mod download
      - run: go vet ./...
      - run: go test ./... -race -coverprofile=coverage.out
      - run: go build ./...

The Full Manual Process: 18 Steps

Here's every step you just went through to fix this one bug:

  1. Notice the error alert or see it in your monitoring tool
  2. Open the error dashboard and read the stack trace
  3. Identify the file and line number from the stack trace
  4. Open your IDE and navigate to the file
  5. Read the surrounding code to understand context
  6. Reproduce the error locally
  7. Identify the root cause
  8. Write the fix
  9. Run the test suite locally
  10. Fix any failing tests
  11. Write new tests covering the edge case
  12. Run the full test suite again
  13. Create a new git branch
  14. Commit and push your changes
  15. Open a pull request
  16. Wait for code review
  17. Merge and deploy to production
  18. Monitor production to confirm the error is resolved

Total time: 30-60 minutes. For one bug.

Or Let bugstack Fix It in Under 2 minutes

Every step above? bugstack does it automatically.

Step 1: Install the SDK

go get github.com/bugstack/sdk

Step 2: Initialize

import "github.com/bugstack/sdk"

func init() {
  bugstack.Init(os.Getenv("BUGSTACK_API_KEY"))
}

Step 3: There is no step 3.

bugstack handles everything from here:

  1. Captures the stack trace and request context
  2. Pulls the relevant source files from your GitHub repo
  3. Analyzes the error and understands the code context
  4. Generates a minimal, verified fix
  5. Runs your existing test suite
  6. Pushes through your CI/CD pipeline
  7. Deploys to production (or opens a PR for review)

Time from error to fix deployed: Under 2 minutes.

Human involvement: zero.

Try bugstack Free →

No credit card. 5-minute setup. Cancel anytime.

Deploying the Fix (Manual Path)

  1. Run go test ./... locally to confirm TLS connections work.
  2. Open a pull request with the TLS configuration changes.
  3. Wait for CI checks to pass on the PR.
  4. Have a teammate review and approve the PR.
  5. Merge to main and verify internal service connections in staging.

Frequently Asked Questions

BugStack validates TLS connections with test certificates, ensures InsecureSkipVerify is not used, and tests CA certificate loading before marking it safe to deploy.

BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.

Only in development or testing environments. In production, always verify certificates. Use a custom CA pool for internal services instead of disabling verification.

Install the ca-certificates package in your Dockerfile, or copy your CA cert to /usr/local/share/ca-certificates/ and run update-ca-certificates. For scratch images, copy the cert bundle from a builder stage.