{"id":"c552bc672e8c0111","repo":"jackc/pgx","slug":"tls-error-on-cancel-connection-w","errorCode":null,"errorMessage":"tls error on cancel connection: %w","messagePattern":"tls error on cancel connection: %w","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"pgconn/pgconn.go","lineNumber":1145,"sourceCode":"\tif ctx != context.Background() {\n\t\tcontextWatcher := ctxwatch.NewContextWatcher(&DeadlineContextWatcherHandler{Conn: cancelConn})\n\t\tcontextWatcher.Watch(ctx)\n\t\tdefer contextWatcher.Unwatch()\n\t}\n\n\t// If the primary connection is encrypted, encrypt the cancel connection the same way so the\n\t// backend pid and secret key are not exposed to a passive network observer. This mirrors libpq's\n\t// PQcancelCreate (PG17+), which reuses the original connection's sslmode/gssencmode for the\n\t// cancel connection. The legacy unencrypted path is still used when the primary connection is\n\t// plaintext (e.g. unix sockets or sslmode=disable).\n\tif pgConn.tlsConfig != nil {\n\t\tvar tlsCancelConn net.Conn\n\t\tif pgConn.config.SSLNegotiation == \"direct\" {\n\t\t\ttlsCancelConn = tls.Client(cancelConn, pgConn.tlsConfig)\n\t\t} else {\n\t\t\ttlsCancelConn, err = startTLS(cancelConn, pgConn.tlsConfig)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"tls error on cancel connection: %w\", err)\n\t\t\t}\n\t\t}\n\t\tcancelConn = tlsCancelConn\n\t\tdefer cancelConn.Close()\n\t}\n\n\tbuf := make([]byte, 12+len(pgConn.secretKey))\n\tbinary.BigEndian.PutUint32(buf[0:4], uint32(len(buf)))\n\tbinary.BigEndian.PutUint32(buf[4:8], 80877102)\n\tbinary.BigEndian.PutUint32(buf[8:12], pgConn.pid)\n\tcopy(buf[12:], pgConn.secretKey)\n\n\tif _, err := cancelConn.Write(buf); err != nil {\n\t\treturn fmt.Errorf(\"write to connection for cancellation: %w\", err)\n\t}\n\n\t// Wait for the cancel request to be acknowledged by the server.\n\t// It copies the behavior of the libpq: https://github.com/postgres/postgres/blob/REL_16_0/src/interfaces/libpq/fe-connect.c#L4946-L4960","sourceCodeStart":1127,"sourceCodeEnd":1163,"githubUrl":"https://github.com/jackc/pgx/blob/ec1a0befd22592cffffdeeb0a50311b506372f4c/pgconn/pgconn.go#L1127-L1163","documentation":"Error \"tls error on cancel connection: %w\" thrown in jackc/pgx.","triggerScenarios":"Thrown at pgconn/pgconn.go:1145 when the library encounters an invalid state.","commonSituations":"See trigger scenarios.","solutions":[],"exampleFix":null,"handlingStrategy":null,"validationCode":null,"typeGuard":null,"tryCatchPattern":null,"preventionTips":[],"tags":[],"analyzedSha":"ec1a0befd22592cffffdeeb0a50311b506372f4c","analyzedAt":"2026-08-04T22:52:11.263Z","schemaVersion":2}