MSP-8976 Up deps

This commit is contained in:
Иван Перлов committed 2026-11-20 17:05:48 +03:00
1 parent ebc3c1dbc5
commit 0d9921bbce
603 files changed
+47715 -13202

No files matched your search

+4 -1
View File
@@ -32,7 +32,10 @@ func (c *PgConn) oauthAuth(ctx context.Context) error {
return err
}
msg, err := c.receiveMessage()
// Leave AuthenticationOk for the startup loop, which validates authentication
// policy and records completion for every authentication method. All other
// responses below fail authentication and cause the connection to close.
msg, err := c.peekMessage()
if err != nil {
return err
}
+39 -20
View File
@@ -28,6 +28,7 @@ import (
"hash"
"slices"
"strconv"
"unicode"
"github.com/jackc/pgx/v5/pgproto3"
"golang.org/x/text/secure/precis"
@@ -39,16 +40,18 @@ const (
scramSHA256PlusName = "SCRAM-SHA-256-PLUS"
)
// Perform SCRAM authentication.
func (c *PgConn) scramAuth(serverAuthMechanisms []string) error {
// Perform SCRAM authentication and report whether the completed exchange used
// channel binding. A mechanism selection alone is not proof of authentication;
// the server signature must be verified before returning channelBound=true.
func (c *PgConn) scramAuth(serverAuthMechanisms []string) (channelBound bool, err error) {
sc, err := newScramClient(serverAuthMechanisms, c.config.Password)
if err != nil {
return err
return false, err
}
serverHasPlus := slices.Contains(sc.serverAuthMechanisms, scramSHA256PlusName)
if c.config.ChannelBinding == "require" && !serverHasPlus {
return errors.New("channel binding required but server does not support SCRAM-SHA-256-PLUS")
return false, errors.New("channel binding required but server does not support SCRAM-SHA-256-PLUS")
}
// If we have a TLS connection and channel binding is not disabled, attempt to
@@ -56,7 +59,7 @@ func (c *PgConn) scramAuth(serverAuthMechanisms []string) error {
if tlsConn, ok := c.conn.(*tls.Conn); ok && c.config.ChannelBinding != "disable" {
certHash, err := getTLSCertificateHash(tlsConn)
if err != nil && c.config.ChannelBinding == "require" {
return fmt.Errorf("channel binding required but failed to get server certificate hash: %w", err)
return false, fmt.Errorf("channel binding required but failed to get server certificate hash: %w", err)
}
// Upgrade to SCRAM-SHA-256-PLUS if we have binding data and the server supports it.
@@ -69,7 +72,7 @@ func (c *PgConn) scramAuth(serverAuthMechanisms []string) error {
}
if c.config.ChannelBinding == "require" && sc.channelBindingData == nil {
return errors.New("channel binding required but channel binding data is not available")
return false, errors.New("channel binding required but channel binding data is not available")
}
// Send client-first-message in a SASLInitialResponse
@@ -80,17 +83,17 @@ func (c *PgConn) scramAuth(serverAuthMechanisms []string) error {
c.frontend.Send(saslInitialResponse)
err = c.flushWithPotentialWriteReadDeadlock()
if err != nil {
return err
return false, err
}
// Receive server-first-message payload in an AuthenticationSASLContinue.
saslContinue, err := c.rxSASLContinue()
if err != nil {
return err
return false, err
}
err = sc.recvServerFirstMessage(saslContinue.Data)
if err != nil {
return err
return false, err
}
// Send client-final-message in a SASLResponse
@@ -100,15 +103,18 @@ func (c *PgConn) scramAuth(serverAuthMechanisms []string) error {
c.frontend.Send(saslResponse)
err = c.flushWithPotentialWriteReadDeadlock()
if err != nil {
return err
return false, err
}
// Receive server-final-message payload in an AuthenticationSASLFinal.
saslFinal, err := c.rxSASLFinal()
if err != nil {
return err
return false, err
}
return sc.recvServerFinalMessage(saslFinal.Data)
if err := sc.recvServerFinalMessage(saslFinal.Data); err != nil {
return false, err
}
return sc.authMechanism == scramSHA256PlusName, nil
}
func (c *PgConn) rxSASLContinue() (*pgproto3.AuthenticationSASLContinue, error) {
@@ -192,16 +198,10 @@ func newScramClient(serverAuthMechanisms []string, password string) (*scramClien
return nil, errors.New("server does not support SCRAM-SHA-256")
}
// precis.OpaqueString is equivalent to SASLprep for password.
var err error
sc.password, err = precis.OpaqueString.String(password)
if err != nil {
// PostgreSQL allows passwords invalid according to SCRAM / SASLprep.
sc.password = password
}
sc.password = normalizeScramPassword(password)
buf := make([]byte, clientNonceLen)
_, err = rand.Read(buf)
_, err := rand.Read(buf)
if err != nil {
return nil, err
}
@@ -211,6 +211,25 @@ func newScramClient(serverAuthMechanisms []string, password string) (*scramClien
return sc, nil
}
// normalizeScramPassword preserves PostgreSQL's raw-password fallback for
// characters that SASLprep considers unassigned. SASLprep uses Unicode 3.2,
// while PRECIS uses newer Unicode tables that can change with x/text or Go
// upgrades. Check the original password before PRECIS can change any bytes.
func normalizeScramPassword(password string) string {
for _, r := range password {
if unicode.Is(saslprepUnassigned, r) {
return password
}
}
normalized, err := precis.OpaqueString.String(password)
if err != nil {
// PostgreSQL allows passwords invalid according to SCRAM / SASLprep.
return password
}
return normalized
}
func (sc *scramClient) clientFirstMessage() []byte {
// The client-first-message is the GS2 header concatenated with the bare
// message (username + client nonce). The GS2 header communicates the
+424 -140
View File
@@ -10,7 +10,6 @@ import (
"maps"
"math"
"net"
"net/url"
"os"
"path/filepath"
"strconv"
@@ -43,6 +42,11 @@ type Config struct {
LookupFunc LookupFunc // e.g. net.Resolver.LookupHost
BuildFrontend BuildFrontendFunc
// MaxProtocolMessageBodyLen is the maximum length of a PostgreSQL wire protocol message body in octets. If a
// message body exceeds this length, reading the message will fail with pgproto3.ExceededMaxBodyLenErr. The default
// value is 0, which means no maximum is enforced.
MaxProtocolMessageBodyLen int
// BuildContextWatcherHandler is called to create a ContextWatcherHandler for a connection. The handler is called
// when a context passed to a PgConn method is canceled.
BuildContextWatcherHandler func(*PgConn) ctxwatch.Handler
@@ -55,6 +59,14 @@ type Config struct {
SSLNegotiation string // sslnegotiation=postgres or sslnegotiation=direct
// SSLCertMode controls client certificate usage. Valid values are "disable", "allow", and "require".
// The default is "allow"; an empty field is also treated as "allow".
// "disable" prevents sending a certificate, even if TLSConfig supplies one.
// "require" rejects successful authentication unless the server requested and the client sent a certificate.
// TLS session resumption is disabled in "require" mode so that every connection exchanges a certificate.
// It does not guarantee that the server validated the certificate.
SSLCertMode string
// AfterNetConnect is called after the network connection, including TLS if applicable, is established but before any
// PostgreSQL protocol communication. It takes the established net.Conn and returns a net.Conn that will be used in
// its place. It can be used to wrap the net.Conn (e.g. for logging, diagnostics, or testing). Its functionality has
@@ -107,8 +119,17 @@ type Config struct {
RequireAuth string
createdByParseConfig bool // Used to enforce created by ParseConfig rule.
// File-backed client certificates are installed only on connection-specific TLS
// configs, so callers can override Certificates or GetClientCertificate.
clientCertificateLoaders map[*tls.Config]func(*tls.CertificateRequestInfo) (*tls.Certificate, error)
}
// defaultPort is the port used when neither the connection string, the environment, nor the
// service file supplies one. It is also the per-element fallback for empty entries in a
// multi-host port list.
const defaultPort = "5432"
// connStringKeyAliases maps libpq parameter keywords to the canonical key names this package
// uses internally in the parsed-settings map. Most keywords are already canonical; this map
// holds only those whose pgx-internal name differs from the libpq spelling.
@@ -137,7 +158,11 @@ type ParseConfigOptions struct {
// defaults are not checked: only keys that originate from the connString argument.
//
// Keys may be given in either their libpq spelling ("dbname") or pgx-internal spelling
// ("database"); both are accepted.
// ("database"); both are accepted. The URI-only ssl=true alias for sslmode=require is
// accepted when either "ssl" or "sslmode" is allowed; an explicit sslmode key or a
// non-"true" ssl value only matches its own spelling. Every ssl/sslmode occurrence in
// the connection string is validated, including occurrences superseded by a later
// repeated parameter.
//
// A nil slice (the default) applies no restriction and matches libpq behaviour. An empty
// non-nil slice rejects every key, i.e. connString must be empty.
@@ -156,8 +181,18 @@ type ParseConfigOptions struct {
func (c *Config) Copy() *Config {
newConf := new(Config)
*newConf = *c
if c.clientCertificateLoaders != nil {
newConf.clientCertificateLoaders = make(map[*tls.Config]func(*tls.CertificateRequestInfo) (*tls.Certificate, error), len(c.clientCertificateLoaders))
}
cloneTLSConfig := func(config *tls.Config) *tls.Config {
cloned := config.Clone()
if loader := c.clientCertificateLoaders[config]; loader != nil {
newConf.clientCertificateLoaders[cloned] = loader
}
return cloned
}
if newConf.TLSConfig != nil {
newConf.TLSConfig = c.TLSConfig.Clone()
newConf.TLSConfig = cloneTLSConfig(c.TLSConfig)
}
if newConf.RuntimeParams != nil {
newConf.RuntimeParams = make(map[string]string, len(c.RuntimeParams))
@@ -169,7 +204,7 @@ func (c *Config) Copy() *Config {
newFallback := new(FallbackConfig)
*newFallback = *fallback
if newFallback.TLSConfig != nil {
newFallback.TLSConfig = fallback.TLSConfig.Clone()
newFallback.TLSConfig = cloneTLSConfig(fallback.TLSConfig)
}
newConf.Fallbacks[i] = newFallback
}
@@ -232,16 +267,21 @@ func NetworkAddress(host string, port uint16) (network, address string) {
// to only read from the environment. If a password is not supplied it will attempt to read the .pgpass file.
//
// # Example Keyword/Value
// user=jack password=secret host=pg.example.com port=5432 dbname=mydb sslmode=verify-ca
// user=jack password=secret host=pg.example.com port=5432 dbname=mydb sslmode=verify-full
//
// # Example URL
// postgres://jack:secret@pg.example.com:5432/mydb?sslmode=verify-ca
// postgres://jack:secret@pg.example.com:5432/mydb?sslmode=verify-full
//
// The returned *Config may be modified. However, it is strongly recommended that any configuration that can be done
// through the connection string be done there. In particular the fields Host, Port, TLSConfig, and Fallbacks can be
// interdependent (e.g. TLSConfig needs knowledge of the host to validate the server certificate). These fields should
// not be modified individually. They should all be modified or all left unchanged.
//
// Client certificates configured with sslcert and sslkey are reloaded for each TLS certificate request.
// Setting TLSConfig.Certificates (including a non-nil empty slice) or TLSConfig.GetClientCertificate overrides
// this behavior. Replacing TLSConfig discards its file-backed certificate settings; use Config.Copy to retain
// those settings when copying a configuration.
//
// ParseConfig supports specifying multiple hosts in similar manner to libpq. Host and port may include comma separated
// values that will be tried in order. This can be used as part of a high availability system. See
// https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-MULTIPLE-HOSTS for more information.
@@ -307,6 +347,21 @@ func NetworkAddress(host string, port uint16) (network, address string) {
// When multiple hosts are specified, libpq allows them to have different passwords set via the .pgpass file. pgconn
// does not.
//
// URL query parameters that libpq does not recognize cause libpq to fail with an "invalid URI query parameter" error.
// ParseConfig accepts them: they become runtime parameters or pgx-specific options (e.g. pool_max_conns).
//
// Connection strings containing a NUL byte are rejected, in both URI and keyword/value form. libpq cannot encounter
// one because its conninfo strings are NUL-terminated C strings, but a Go string can carry a NUL into the startup
// packet, where it delimits parameters rather than being data. Settings reaching Config by other routes (a service
// file, or direct assignment to Config.RuntimeParams, User, or Database) are not checked here; a NUL in those is
// caught when the startup message is encoded, and Connect fails rather than sending it.
//
// Error messages from ParseConfig avoid quoting the unredacted connection string and attempt to redact recognizable
// password fields, while libpq quotes the failing input verbatim. This redaction is best effort. An invalid connection
// string can be structurally ambiguous, so pgconn cannot guarantee that every password in malformed input will be
// identified or redacted. Applications should not assume that parse errors are safe to expose when connection strings
// may contain secrets.
//
// In addition, ParseConfig accepts the following options:
//
// - servicefile.
@@ -325,11 +380,12 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con
envSettings := parseEnvSettings()
connStringSettings := make(map[string]string)
var urlMeta parseURLMeta
if connString != "" {
var err error
// connString may be a database URL or in PostgreSQL keyword/value format
if strings.HasPrefix(connString, "postgres://") || strings.HasPrefix(connString, "postgresql://") {
connStringSettings, err = parseURLSettings(connString)
connStringSettings, urlMeta, err = parseURLSettings(connString)
if err != nil {
return nil, &ParseConfigError{ConnString: connString, msg: "failed to parse as URL", err: err}
}
@@ -346,14 +402,77 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con
for _, k := range options.ConnStringAllowedKeys {
allowed[canonicalConnStringKey(k)] = struct{}{}
}
notAllowed := func(k string) error {
return &ParseConfigError{ConnString: connString, msg: fmt.Sprintf("connection string key %q is not in ConnStringAllowedKeys", k)}
}
_, sslAllowed := allowed["ssl"]
_, sslmodeAllowed := allowed["sslmode"]
// Repeated-key handling and the URI ssl=true alias rewrite can remove
// ssl/sslmode occurrences from the final settings map, so those two keys
// are validated from what the user actually wrote -- every occurrence,
// fail closed -- rather than from what survived. The alias itself is
// accepted under either spelling, the same way dbname/database are
// interchangeable; an explicit sslmode key or a non-"true" ssl value
// only matches its own spelling.
if urlMeta.sawRawSSLKey && !sslAllowed {
return nil, notAllowed("ssl")
}
if urlMeta.sawExplicitSSLModeKey && !sslmodeAllowed {
return nil, notAllowed("sslmode")
}
if urlMeta.sawSSLTrueAlias && !sslAllowed && !sslmodeAllowed {
return nil, notAllowed("ssl")
}
for k := range connStringSettings {
if _, ok := allowed[k]; !ok {
return nil, &ParseConfigError{ConnString: connString, msg: fmt.Sprintf("connection string key %q is not in ConnStringAllowedKeys", k)}
if _, ok := allowed[k]; ok {
continue
}
// A multi-host URI with no explicit ports produces an implied
// all-empty port list (e.g. ","), matching libpq. Only that list
// -- identified by the parser from the raw syntax, not inferred
// from the value -- is exempt from the allow-list: it carries no
// user-supplied port text. An explicit empty port (?port= in a
// URI or port= in keyword/value form) is user-supplied, and
// because a present-but-empty port still shadows PGPORT it must
// pass the allow-list like any other key.
if k == "port" && urlMeta.impliedEmptyPortList {
continue
}
// A surviving ssl or sslmode entry from a URI was already
// validated above against every spelling the user wrote.
if k == "ssl" && urlMeta.sawRawSSLKey {
continue
}
if k == "sslmode" && (urlMeta.sawSSLTrueAlias || urlMeta.sawExplicitSSLModeKey) {
continue
}
return nil, notAllowed(k)
}
}
settings := mergeSettings(defaultSettings, envSettings, connStringSettings)
// The home-directory-derived defaults (passfile, servicefile, sslcert,
// sslkey, sslrootcert) are already present in settings at this point:
// defaultSettings resolves them via the user's home directory, which is
// safe and cheap to look up (see defaults.go / defaults_windows.go).
//
// The default PostgreSQL user name is different: resolving it requires
// looking up the OS user account, which can be slow or, in some
// restricted container environments, crash the process. So that lookup
// is memoized and only performed lazily below, the first time it is
// actually needed -- i.e. only when a connection string or environment
// does not already supply a user.
var cachedOSUserSettings map[string]string
lazyOSUserSettings := func() map[string]string {
if cachedOSUserSettings == nil {
cachedOSUserSettings = osUserSettings()
}
return cachedOSUserSettings
}
if service, present := settings["service"]; present {
serviceSettings, err := parseServiceSettings(settings["servicefile"], service)
if err != nil {
@@ -363,6 +482,13 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con
settings = mergeSettings(defaultSettings, envSettings, serviceSettings, connStringSettings)
}
// Only fall back to the OS user account for the default PostgreSQL user
// name when it was not already supplied by the connection string,
// environment, or service file.
if settings["user"] == "" {
settings = mergeSettings(lazyOSUserSettings(), settings)
}
config := &Config{
createdByParseConfig: true,
Database: settings["database"],
@@ -382,6 +508,16 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con
},
}
sslCertMode, present := settings["sslcertmode"]
if !present {
sslCertMode = "allow"
}
var err error
config.SSLCertMode, err = parseSSLCertMode(sslCertMode)
if err != nil {
return nil, &ParseConfigError{ConnString: connString, msg: "invalid sslcertmode", err: err}
}
if connectTimeoutSetting, present := settings["connect_timeout"]; present {
connectTimeout, err := parseConnectTimeoutSetting(connectTimeoutSetting)
if err != nil {
@@ -407,6 +543,7 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con
"sslmode": {},
"sslkey": {},
"sslcert": {},
"sslcertmode": {},
"sslrootcert": {},
"sslnegotiation": {},
"sslpassword": {},
@@ -442,17 +579,41 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con
hosts := strings.Split(settings["host"], ",")
ports := strings.Split(settings["port"], ",")
// Like libpq, if exactly one port is given it applies to all hosts;
// otherwise there must be exactly one port per host. Empty list elements
// mean "use the default".
if len(ports) > 1 && len(ports) != len(hosts) {
return nil, &ParseConfigError{ConnString: connString, msg: fmt.Sprintf("could not match %d port numbers to %d hosts", len(ports), len(hosts))}
}
// defaultHost stats candidate socket directories, so resolve it at most
// once even when several host list elements are empty. It never returns "".
resolvedDefaultHost := ""
for i, host := range hosts {
var portStr string
if i < len(ports) {
portStr = ports[i]
} else {
portStr = ports[0]
if host == "" {
if resolvedDefaultHost == "" {
resolvedDefaultHost = defaultHost()
}
host = resolvedDefaultHost
}
portStr := ports[0]
if len(ports) > 1 {
portStr = ports[i]
}
if portStr == "" {
portStr = defaultPort
}
// The strconv error is deliberately not wrapped: it quotes the
// offending text, and in a malformed URI the bytes that land in the
// port position can be a mislaid password (postgres://u:sec:ret@h
// parses "sec:ret@h" as the port). The best-effort-redacted connection
// string in ParseConfigError provides the available context without
// deliberately quoting the offending port text again.
port, err := parsePort(portStr)
if err != nil {
return nil, &ParseConfigError{ConnString: connString, msg: "invalid port", err: err}
return nil, &ParseConfigError{ConnString: connString, msg: "invalid port"}
}
var tlsConfigs []*tls.Config
@@ -462,7 +623,7 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con
tlsConfigs = append(tlsConfigs, nil)
} else {
var err error
tlsConfigs, err = configTLS(settings, host, options)
tlsConfigs, err = config.configTLS(settings, host, options)
if err != nil {
return nil, &ParseConfigError{ConnString: connString, msg: "failed to configure TLS", err: err}
}
@@ -483,14 +644,13 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con
config.Fallbacks = fallbacks[1:]
config.SSLNegotiation = settings["sslnegotiation"]
passfile, err := pgpassfile.ReadPassfile(settings["passfile"])
if err == nil {
if config.Password == "" {
if config.Password == "" {
passfile, err := pgpassfile.ReadPassfile(settings["passfile"])
if err == nil {
host := config.Host
if network, _ := NetworkAddress(config.Host, config.Port); network == "unix" {
host = "localhost"
}
config.Password = passfile.FindPassword(host, strconv.Itoa(int(config.Port)), config.Database, config.User)
}
}
@@ -591,6 +751,7 @@ func parseEnvSettings() map[string]string {
"PGSSLMODE": "sslmode",
"PGSSLKEY": "sslkey",
"PGSSLCERT": "sslcert",
"PGSSLCERTMODE": "sslcertmode",
"PGSSLSNI": "sslsni",
"PGSSLROOTCERT": "sslrootcert",
"PGSSLPASSWORD": "sslpassword",
@@ -607,8 +768,9 @@ func parseEnvSettings() map[string]string {
}
for envname, realname := range nameMap {
value := os.Getenv(envname)
if value != "" {
value, present := os.LookupEnv(envname)
// Preserve an explicitly empty sslcertmode so it is rejected, like libpq.
if value != "" || (present && realname == "sslcertmode") {
settings[realname] = value
}
}
@@ -616,76 +778,46 @@ func parseEnvSettings() map[string]string {
return settings
}
func parseURLSettings(connString string) (map[string]string, error) {
settings := make(map[string]string)
parsedURL, err := url.Parse(connString)
if err != nil {
if urlErr := new(url.Error); errors.As(err, &urlErr) {
return nil, urlErr.Err
}
return nil, err
}
if parsedURL.User != nil {
if u := parsedURL.User.Username(); u != "" {
settings["user"] = u
}
if password, present := parsedURL.User.Password(); present {
settings["password"] = password
}
}
// Handle multiple host:port's in url.Host by splitting them into host,host,host and port,port,port.
var hosts []string
var ports []string
for host := range strings.SplitSeq(parsedURL.Host, ",") {
if host == "" {
continue
}
if isIPOnly(host) {
hosts = append(hosts, strings.Trim(host, "[]"))
continue
}
h, p, err := net.SplitHostPort(host)
if err != nil {
return nil, fmt.Errorf("failed to split host:port in '%s', err: %w", host, err)
}
if h != "" {
hosts = append(hosts, h)
}
if p != "" {
ports = append(ports, p)
}
}
if len(hosts) > 0 {
settings["host"] = strings.Join(hosts, ",")
}
if len(ports) > 0 {
settings["port"] = strings.Join(ports, ",")
}
database := strings.TrimLeft(parsedURL.Path, "/")
if database != "" {
settings["database"] = database
}
for k, v := range parsedURL.Query() {
settings[canonicalConnStringKey(k)] = v[0]
}
return settings, nil
}
func isIPOnly(host string) bool {
return net.ParseIP(strings.Trim(host, "[]")) != nil || !strings.Contains(host, ":")
}
var asciiSpace = [256]uint8{'\t': 1, '\n': 1, '\v': 1, '\f': 1, '\r': 1, ' ': 1}
// unescapeKeywordValue applies libpq's backslash rule to the raw text of a
// keyword/value value: a backslash is dropped and whatever follows it is taken
// literally, whatever that character is. A backslash at the very end escapes
// the end of the string, so it is dropped and contributes nothing -- which is
// how libpq accepts `host=a\`. Only the unquoted branch can reach that case;
// inside quotes the escaped terminator leaves the string unterminated and the
// caller has already rejected it.
func unescapeKeywordValue(s string) string {
if !strings.ContainsRune(s, '\\') {
return s
}
var sb strings.Builder
sb.Grow(len(s))
for i := 0; i < len(s); i++ {
if s[i] == '\\' {
i++
if i == len(s) {
break
}
}
sb.WriteByte(s[i])
}
return sb.String()
}
func parseKeywordValueSettings(s string) (map[string]string, error) {
settings := make(map[string]string)
// Reject NUL bytes up front, as parseURLSettings does. libpq never sees one
// because its conninfo strings are NUL-terminated C strings; a Go string can
// carry a NUL through to the startup packet, where it acts as a parameter
// delimiter rather than data. StartupMessage.Encode refuses such parameters,
// but failing here reports the problem against the input that caused it.
if strings.IndexByte(s, 0) >= 0 {
return nil, errors.New("forbidden NUL byte in connection string")
}
// Trim any leading whitespace so that the loop exits cleanly when only
// spaces remain (e.g. trailing spaces after the last value).
s = strings.TrimLeft(s, " \t\n\r\v\f")
@@ -697,6 +829,15 @@ func parseKeywordValueSettings(s string) (map[string]string, error) {
}
key = strings.Trim(s[:eqIdx], " \t\n\r\v\f")
// libpq reads a keyword as a run of non-space characters and then
// requires the next non-space character to be '=', so whitespace
// inside a keyword terminates it and is an error. Trimming alone would
// accept the space as part of the key and turn a typo into a bogus
// RuntimeParam that only the server rejects. Report it as libpq does,
// naming the keyword it had read.
if i := strings.IndexAny(key, " \t\n\r\v\f"); i >= 0 {
return nil, fmt.Errorf(`missing "=" after %q in connection info string`, key[:i])
}
s = strings.TrimLeft(s[eqIdx+1:], " \t\n\r\v\f")
switch {
case len(s) == 0:
@@ -708,12 +849,15 @@ func parseKeywordValueSettings(s string) (map[string]string, error) {
}
if s[end] == '\\' {
end++
// A trailing backslash escapes the end of the string.
// libpq drops it and ends the value there. Break rather
// than let the loop's post-increment push end past len(s).
if end == len(s) {
return nil, errors.New("invalid backslash")
break
}
}
}
val = strings.ReplaceAll(strings.ReplaceAll(s[:end], "\\\\", "\\"), "\\'", "'")
val = unescapeKeywordValue(s[:end])
// Consume the value and trim any subsequent whitespace so that
// multiple trailing spaces don't cause a spurious parse failure.
s = strings.TrimLeft(s[end:], " \t\n\r\v\f")
@@ -726,12 +870,15 @@ func parseKeywordValueSettings(s string) (map[string]string, error) {
}
if s[end] == '\\' {
end++
if end == len(s) {
return nil, errors.New("unterminated quoted string in connection info string")
}
}
}
if end == len(s) {
return nil, errors.New("unterminated quoted string in connection info string")
}
val = strings.ReplaceAll(strings.ReplaceAll(s[:end], "\\\\", "\\"), "\\'", "'")
val = unescapeKeywordValue(s[:end])
// Consume the closing quote and any subsequent whitespace.
s = strings.TrimLeft(s[end+1:], " \t\n\r\v\f")
}
@@ -773,12 +920,16 @@ func parseServiceSettings(servicefilePath, serviceName string) (map[string]strin
// configTLS uses libpq's TLS parameters to construct []*tls.Config. It is
// necessary to allow returning multiple TLS configs as sslmode "allow" and
// "prefer" allow fallback.
func configTLS(settings map[string]string, thisHost string, parseConfigOptions ParseConfigOptions) ([]*tls.Config, error) {
func (c *Config) configTLS(settings map[string]string, thisHost string, parseConfigOptions ParseConfigOptions) ([]*tls.Config, error) {
host := thisHost
sslmode := settings["sslmode"]
sslrootcert := settings["sslrootcert"]
sslcert := settings["sslcert"]
sslkey := settings["sslkey"]
if settings["sslcertmode"] == "disable" {
// Like libpq, do not read client certificate or key files in this mode.
sslcert, sslkey = "", ""
}
sslpassword := settings["sslpassword"]
sslsni := settings["sslsni"]
sslnegotiation := settings["sslnegotiation"]
@@ -892,57 +1043,41 @@ func configTLS(settings map[string]string, thisHost string, parseConfigOptions P
}
if sslcert != "" && sslkey != "" {
buf, err := os.ReadFile(sslkey)
// Retain the directory used at parse time, while still following symlinks
// on each load so certificate rotation can replace their targets.
var err error
sslcert, err = filepath.Abs(sslcert)
if err != nil {
return nil, fmt.Errorf("unable to read sslkey: %w", err)
return nil, fmt.Errorf("unable to resolve sslcert: %w", err)
}
block, _ := pem.Decode(buf)
if block == nil {
return nil, errors.New("failed to decode sslkey")
sslkey, err = filepath.Abs(sslkey)
if err != nil {
return nil, fmt.Errorf("unable to resolve sslkey: %w", err)
}
var pemKey []byte
var decryptedKey []byte
var decryptedError error
// If PEM is encrypted, attempt to decrypt using pass phrase
if x509.IsEncryptedPEMBlock(block) {
// Attempt decryption with pass phrase
// NOTE: only supports RSA (PKCS#1)
if sslpassword != "" {
decryptedKey, decryptedError = x509.DecryptPEMBlock(block, []byte(sslpassword)) //nolint:ineffassign
}
// if sslpassword not provided or has decryption error when use it
// try to find sslpassword with callback function
if sslpassword == "" || decryptedError != nil {
if parseConfigOptions.GetSSLPassword != nil {
sslpassword = parseConfigOptions.GetSSLPassword(context.Background())
}
if sslpassword == "" {
return nil, fmt.Errorf("unable to find sslpassword")
}
}
decryptedKey, decryptedError = x509.DecryptPEMBlock(block, []byte(sslpassword))
// Should we also provide warning for PKCS#1 needed?
if decryptedError != nil {
return nil, fmt.Errorf("unable to decrypt key: %w", decryptedError)
// Read the key & cert so
// (a) we can provide error feedback now and
// (b) invoke the GetSSLPassword callback once if necessary
_, resolvedPassword, err := loadClientCertificate(sslcert, sslkey, sslpassword, parseConfigOptions)
if err != nil {
return nil, err
}
if c.clientCertificateLoaders == nil {
c.clientCertificateLoaders = make(map[*tls.Config]func(*tls.CertificateRequestInfo) (*tls.Certificate, error))
}
c.clientCertificateLoaders[tlsConfig] = func(cri *tls.CertificateRequestInfo) (*tls.Certificate, error) {
cert, _, err := loadClientCertificate(sslcert, sslkey, resolvedPassword, ParseConfigOptions{})
if err != nil {
return nil, err
}
pemBytes := pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: decryptedKey,
// Same check crypto/tls provides when passing certs through config.Certificates
if cri != nil && cri.SupportsCertificate(&cert) != nil {
return new(tls.Certificate), nil
}
pemKey = pem.EncodeToMemory(&pemBytes)
} else {
pemKey = pem.EncodeToMemory(block)
return &cert, nil
}
certfile, err := os.ReadFile(sslcert)
if err != nil {
return nil, fmt.Errorf("unable to read cert: %w", err)
}
cert, err := tls.X509KeyPair(certfile, pemKey)
if err != nil {
return nil, fmt.Errorf("unable to load cert: %w", err)
}
tlsConfig.Certificates = []tls.Certificate{cert}
}
// Set Server Name Indication (SNI), if enabled by connection parameters.
@@ -964,6 +1099,144 @@ func configTLS(settings map[string]string, thisHost string, parseConfigOptions P
}
}
// loadClientCertificate reads sslcert and sslkey and returns the pair, along
// with the password that decrypted the key (empty when the key is not
// encrypted). When the key is encrypted and sslpassword does not decrypt it,
// parseConfigOptions.GetSSLPassword is asked for one.
func loadClientCertificate(sslcert, sslkey, sslpassword string, parseConfigOptions ParseConfigOptions) (tls.Certificate, string, error) {
buf, err := os.ReadFile(sslkey)
if err != nil {
return tls.Certificate{}, "", fmt.Errorf("unable to read sslkey: %w", err)
}
block, _ := pem.Decode(buf)
if block == nil {
return tls.Certificate{}, "", errors.New("failed to decode sslkey")
}
var pemKey []byte
var decryptedKey []byte
var decryptedError error
// If PEM is encrypted, attempt to decrypt using pass phrase
if x509.IsEncryptedPEMBlock(block) {
// Attempt decryption with pass phrase
if sslpassword != "" {
decryptedKey, decryptedError = x509.DecryptPEMBlock(block, []byte(sslpassword)) //nolint:ineffassign
}
// if sslpassword not provided or has decryption error when use it
// try to find sslpassword with callback function
if sslpassword == "" || decryptedError != nil {
if parseConfigOptions.GetSSLPassword != nil {
sslpassword = parseConfigOptions.GetSSLPassword(context.Background())
}
if sslpassword == "" {
return tls.Certificate{}, "", fmt.Errorf("unable to find sslpassword")
}
}
decryptedKey, decryptedError = x509.DecryptPEMBlock(block, []byte(sslpassword))
if decryptedError != nil {
return tls.Certificate{}, "", fmt.Errorf("unable to decrypt key: %w", decryptedError)
}
pemBytes := pem.Block{
// Preserve the old loader's tolerance of non-key PEM labels.
// X509KeyPair determines the key format from the decrypted DER.
Type: "PRIVATE KEY",
Bytes: decryptedKey,
}
pemKey = pem.EncodeToMemory(&pemBytes)
} else {
// Hand over the whole file rather than the first block: X509KeyPair
// skips blocks that are not a key, so a combined key+certificate file
// works whatever order it is written in.
pemKey = buf
}
certfile, err := os.ReadFile(sslcert)
if err != nil {
return tls.Certificate{}, "", fmt.Errorf("unable to read cert: %w", err)
}
cert, err := tls.X509KeyPair(certfile, pemKey)
if err != nil {
return tls.Certificate{}, "", fmt.Errorf("unable to load cert: %w", err)
}
return cert, sslpassword, nil
}
type sslCertState struct {
requested bool
sent bool
}
// checkRequired verifies the required certificate exchange during connection startup.
// In require mode, a nil state means that no TLS connection was made.
func (s *sslCertState) checkRequired() error {
if s == nil || !s.requested {
return &sslCertModeError{msg: "server did not request an SSL certificate"}
}
if !s.sent {
return &sslCertModeError{msg: "server accepted connection without a valid SSL certificate"}
}
return nil
}
// prepareTLSConfigForConnect prepares certificate reloading and sslcertmode for one connection.
// In require mode, the returned state must be checked before accepting AuthenticationOk or ReadyForQuery.
// Configs may be shared by concurrent connection attempts, so any callback state must
// belong to a clone made for this attempt, not the original config.
func (c *Config) prepareTLSConfigForConnect(config *tls.Config) (*tls.Config, *sslCertState) {
if c.SSLCertMode != "disable" && config.Certificates == nil && config.GetClientCertificate == nil {
if loader := c.clientCertificateLoaders[config]; loader != nil {
config = config.Clone()
config.GetClientCertificate = loader
}
}
switch c.SSLCertMode {
case "disable":
config = config.Clone()
config.Certificates = nil
config.GetClientCertificate = func(*tls.CertificateRequestInfo) (*tls.Certificate, error) {
return new(tls.Certificate), nil
}
return config, nil
case "require":
state := new(sslCertState)
original := config
config = config.Clone()
// Resumed sessions skip the certificate exchange and its callback.
config.ClientSessionCache = nil
config.GetClientCertificate = func(cri *tls.CertificateRequestInfo) (*tls.Certificate, error) {
state.requested = true
var cert *tls.Certificate
var err error
if original.GetClientCertificate != nil {
cert, err = original.GetClientCertificate(cri)
} else {
// Preserve crypto/tls's default certificate selection, including its
// signature scheme and acceptable CA checks.
cert = new(tls.Certificate)
for i := range original.Certificates {
if cri.SupportsCertificate(&original.Certificates[i]) == nil {
cert = &original.Certificates[i]
break
}
}
}
state.sent = err == nil && cert != nil && len(cert.Certificate) > 0
return cert, err
}
return config, state
default:
return config, nil
}
}
func parseSSLCertMode(s string) (string, error) {
switch s {
case "disable", "allow", "require":
return s, nil
default:
return "", fmt.Errorf("unknown sslcertmode value: %v", s)
}
}
func parsePort(s string) (uint16, error) {
port, err := strconv.ParseUint(s, 10, 16)
if err != nil {
@@ -1001,6 +1274,17 @@ func makeConnectTimeoutDialFunc(timeout time.Duration) DialFunc {
return d.DialContext
}
var (
// ErrReadOnlyConnection is returned when a read-write connection is required but the connection is read-only.
ErrReadOnlyConnection = errors.New("read only connection")
// ErrReadWriteConnection is returned when a read-only connection is required but the connection is read-write.
ErrReadWriteConnection = errors.New("connection is not read only")
// ErrPrimaryConnection is returned when a standby connection is required but the server is primary.
ErrPrimaryConnection = errors.New("server is not in hot standby mode")
// ErrStandbyConnection is returned when a primary connection is required but the server is in standby mode.
ErrStandbyConnection = errors.New("server is in standby mode")
)
// ValidateConnectTargetSessionAttrsReadWrite is a ValidateConnectFunc that implements libpq compatible
// target_session_attrs=read-write.
func ValidateConnectTargetSessionAttrsReadWrite(ctx context.Context, pgConn *PgConn) error {
@@ -1010,7 +1294,7 @@ func ValidateConnectTargetSessionAttrsReadWrite(ctx context.Context, pgConn *PgC
}
if string(result[0].Rows[0][0]) == "on" {
return errors.New("read only connection")
return ErrReadOnlyConnection
}
return nil
@@ -1025,7 +1309,7 @@ func ValidateConnectTargetSessionAttrsReadOnly(ctx context.Context, pgConn *PgCo
}
if string(result[0].Rows[0][0]) != "on" {
return errors.New("connection is not read only")
return ErrReadWriteConnection
}
return nil
@@ -1040,7 +1324,7 @@ func ValidateConnectTargetSessionAttrsStandby(ctx context.Context, pgConn *PgCon
}
if string(result[0].Rows[0][0]) != "t" {
return errors.New("server is not in hot standby mode")
return ErrPrimaryConnection
}
return nil
@@ -1055,7 +1339,7 @@ func ValidateConnectTargetSessionAttrsPrimary(ctx context.Context, pgConn *PgCon
}
if string(result[0].Rows[0][0]) == "t" {
return errors.New("server is in standby mode")
return ErrStandbyConnection
}
return nil
@@ -1070,7 +1354,7 @@ func ValidateConnectTargetSessionAttrsPreferStandby(ctx context.Context, pgConn
}
if string(result[0].Rows[0][0]) != "t" {
return &NotPreferredError{err: errors.New("server is not in hot standby mode")}
return &NotPreferredError{err: ErrPrimaryConnection}
}
return nil
+57 -14
View File
@@ -1,5 +1,4 @@
//go:build !windows
// +build !windows
package pgconn
@@ -9,22 +8,46 @@ import (
"path/filepath"
)
// currentOSUser resolves the current OS user account. It is a seam so tests
// can simulate os/user.Current failing -- including the unrecoverable
// crashes reported in some restricted/broken-NSS container environments --
// without needing such an environment.
var currentOSUser = user.Current
// userHomeDir resolves the current user's home directory. It is a seam so
// tests can simulate os.UserHomeDir failing without needing to unset $HOME
// for the whole process.
//
// os.UserHomeDir only reads the $HOME environment variable on this platform;
// it never calls into cgo or NSS, so unlike os/user.Current it cannot crash
// in restricted/broken container environments. That also means it can
// resolve a different directory than the OS account's passwd-file home
// directory if $HOME has been overridden -- this is an accepted tradeoff so
// that home-directory-derived defaults (pgpass, pg_service.conf, client SSL
// certificate/key/root files) keep resolving even when the OS user account
// lookup itself is unavailable or unsafe to call.
var userHomeDir = os.UserHomeDir
func defaultSettings() map[string]string {
settings := make(map[string]string)
settings["host"] = defaultHost()
settings["port"] = "5432"
settings["port"] = defaultPort
settings["target_session_attrs"] = "any"
// Default to the OS user name. Purposely ignoring err getting user name from
// OS. The client application will simply have to specify the user in that
// case (which they typically will be doing anyway).
user, err := user.Current()
if err == nil {
settings["user"] = user.Username
settings["passfile"] = filepath.Join(user.HomeDir, ".pgpass")
settings["servicefile"] = filepath.Join(user.HomeDir, ".pg_service.conf")
sslcert := filepath.Join(user.HomeDir, ".postgresql", "postgresql.crt")
sslkey := filepath.Join(user.HomeDir, ".postgresql", "postgresql.key")
// The home-directory-derived defaults (~/.pgpass, ~/.pg_service.conf,
// and the client SSL certificate/key/root files under ~/.postgresql)
// only need the user's home directory, not the full OS user account, so
// they are resolved unconditionally here via os.UserHomeDir. This keeps
// them available even when looking up the OS user account (needed only
// for the default PostgreSQL user name, see osUserSettings) is slow,
// fails, or -- in some restricted container environments with a broken
// NSS/CGO setup -- would crash the process.
if homeDir, err := userHomeDir(); err == nil {
settings["passfile"] = filepath.Join(homeDir, ".pgpass")
settings["servicefile"] = filepath.Join(homeDir, ".pg_service.conf")
sslcert := filepath.Join(homeDir, ".postgresql", "postgresql.crt")
sslkey := filepath.Join(homeDir, ".postgresql", "postgresql.key")
if _, err := os.Stat(sslcert); err == nil {
if _, err := os.Stat(sslkey); err == nil {
// Both the cert and key must be present to use them, or do not use either
@@ -32,13 +55,33 @@ func defaultSettings() map[string]string {
settings["sslkey"] = sslkey
}
}
sslrootcert := filepath.Join(user.HomeDir, ".postgresql", "root.crt")
sslrootcert := filepath.Join(homeDir, ".postgresql", "root.crt")
if _, err := os.Stat(sslrootcert); err == nil {
settings["sslrootcert"] = sslrootcert
}
}
settings["target_session_attrs"] = "any"
return settings
}
// osUserSettings returns the default PostgreSQL user name derived from the
// current OS user account.
//
// Resolving this requires looking up the OS user account, which can be slow
// or, in some restricted container environments (e.g. distroless images
// with a broken NSS/CGO setup), crash the process. Callers must only call
// osUserSettings when the default user name is not already supplied by the
// connection string, environment, or service file.
func osUserSettings() map[string]string {
settings := make(map[string]string)
// Default to the OS user name. Purposely ignoring err getting user name from
// OS. The client application will simply have to specify the user in that
// case (which they typically will be doing anyway).
user, err := currentOSUser()
if err == nil {
settings["user"] = user.Username
}
return settings
}
+77 -17
View File
@@ -7,28 +7,45 @@ import (
"strings"
)
// currentOSUser resolves the current OS user account. It is a seam so tests
// can simulate os/user.Current failing -- including the unrecoverable
// crashes reported in some restricted/broken-NSS container environments --
// without needing such an environment.
var currentOSUser = user.Current
// userHomeDir resolves the current user's home directory. It is a seam so
// tests can simulate os.UserHomeDir failing without needing to unset the
// relevant environment variables for the whole process.
//
// os.UserHomeDir only reads %USERPROFILE% (falling back to
// %HOMEDRIVE%+%HOMEPATH%) on this platform; it never calls into the Windows
// user account APIs, so unlike os/user.Current it cannot crash in
// restricted/broken container environments. That also means it can resolve
// a different directory than the OS account API's reported home directory
// if those environment variables have been overridden -- this is an
// accepted tradeoff so that home-directory-derived defaults (pg_service.conf)
// keep resolving even when the OS user account lookup itself is unavailable
// or unsafe to call.
var userHomeDir = os.UserHomeDir
func defaultSettings() map[string]string {
settings := make(map[string]string)
settings["host"] = defaultHost()
settings["port"] = "5432"
settings["port"] = defaultPort
settings["target_session_attrs"] = "any"
// Default to the OS user name. Purposely ignoring err getting user name from
// OS. The client application will simply have to specify the user in that
// case (which they typically will be doing anyway).
user, err := user.Current()
appData := os.Getenv("APPDATA")
if err == nil {
// Windows gives us the username here as `DOMAIN\user` or `LOCALPCNAME\user`,
// but the libpq default is just the `user` portion, so we strip off the first part.
username := user.Username
if strings.Contains(username, "\\") {
username = username[strings.LastIndex(username, "\\")+1:]
}
settings["user"] = username
// The %APPDATA%\postgresql-derived defaults (pgpass.conf, .pg_service.conf
// and the client SSL certificate/key/root files) only need the APPDATA
// environment variable, not the full OS user account, so they are resolved
// unconditionally here. This keeps them available even when looking up
// the OS user account (needed only for the default PostgreSQL user
// name, see osUserSettings) is slow, fails, or -- in some restricted
// container environments with a broken NSS/CGO setup -- would crash the
// process.
if appData := os.Getenv("APPDATA"); appData != "" {
settings["passfile"] = filepath.Join(appData, "postgresql", "pgpass.conf")
settings["servicefile"] = filepath.Join(user.HomeDir, ".pg_service.conf")
settings["servicefile"] = filepath.Join(appData, "postgresql", ".pg_service.conf")
sslcert := filepath.Join(appData, "postgresql", "postgresql.crt")
sslkey := filepath.Join(appData, "postgresql", "postgresql.key")
if _, err := os.Stat(sslcert); err == nil {
@@ -44,7 +61,50 @@ func defaultSettings() map[string]string {
}
}
settings["target_session_attrs"] = "any"
// libpq looks for the service file at %APPDATA%\postgresql\.pg_service.conf
// on Windows, but pgx used to look for it at ~/.pg_service.conf. Keep
// using that file when there is none at the libpq location, so existing
// setups keep working. The home directory is resolved the same crash-safe
// way as on other platforms (see defaults.go).
if homeDir, err := userHomeDir(); err == nil {
homeServicefile := filepath.Join(homeDir, ".pg_service.conf")
if servicefile, ok := settings["servicefile"]; !ok {
settings["servicefile"] = homeServicefile
} else if _, err := os.Stat(servicefile); os.IsNotExist(err) {
if _, err := os.Stat(homeServicefile); err == nil {
settings["servicefile"] = homeServicefile
}
}
}
return settings
}
// osUserSettings returns the default PostgreSQL user name derived from the
// current OS user account.
//
// Resolving this requires looking up the OS user account, which can be slow
// or, in some restricted container environments (e.g. distroless images
// with a broken NSS/CGO setup), crash the process. Callers must only call
// osUserSettings when the default user name is not already supplied by the
// connection string, environment, or service file.
func osUserSettings() map[string]string {
settings := make(map[string]string)
// Default to the OS user name. Purposely ignoring err getting user name from
// OS. The client application will simply have to specify the user in that
// case (which they typically will be doing anyway).
user, err := currentOSUser()
if err == nil {
// Windows gives us the username here as `DOMAIN\user` or `LOCALPCNAME\user`,
// but the libpq default is just the `user` portion, so we strip off the first part.
username := user.Username
if strings.Contains(username, "\\") {
username = username[strings.LastIndex(username, "\\")+1:]
}
settings["user"] = username
}
return settings
}
+12
View File
@@ -34,6 +34,18 @@ explicitly:
These parameters may also be set via the PGSSLMODE, PGSSLROOTCERT, PGCHANNELBINDING, and PGREQUIREAUTH environment
variables.
Client Certificates
The sslcertmode connection parameter (or PGSSLCERTMODE environment variable) controls whether a client certificate
is sent. The default, allow, sends a certificate if the server requests one and a suitable certificate is available.
The disable mode prevents sending a certificate, including certificates supplied through Config.TLSConfig, and skips
loading sslcert and sslkey files. The require mode fails if the server successfully authenticates the client without
requesting and receiving a client certificate. It does not guarantee that the server validated the certificate.
If this check fails, no further TLS or host fallbacks are tried.
TLS session resumption is disabled in require mode so every connection exchanges a certificate.
An explicitly empty sslcertmode parameter or PGSSLCERTMODE environment variable is invalid.
This parameter is independent of sslmode, which controls TLS and server certificate verification.
Executing a Query
ExecParams and ExecPrepared execute a single query. They return readers that iterate over each row. The Read method
+180 -16
View File
@@ -5,7 +5,6 @@ import (
"errors"
"fmt"
"net"
"net/url"
"regexp"
"strings"
)
@@ -93,10 +92,20 @@ func (e *perDialConnectError) Unwrap() error {
return e.err
}
// sslCertModeError is a client-side authentication failure that must stop
// connection fallback, matching libpq's sslcertmode=require behavior.
type sslCertModeError struct {
msg string
}
func (e *sslCertModeError) Error() string {
return e.msg
}
// ErrConnClosed is returned (possibly wrapped) when an operation is attempted
// on a connection that the driver has already closed, e.g. because a prior
// query was cancelled mid-flight or the underlying socket went away. Use
// errors.Is to test for it, since it shows up wrapped inside connLockError.
// errors.Is to test for it, since it is usually wrapped in another error.
var ErrConnClosed = errors.New("conn closed")
type connLockError struct {
@@ -118,9 +127,11 @@ func (e *connLockError) Unwrap() error {
return nil
}
// ParseConfigError is the error returned when a connection string cannot be parsed.
// ParseConfigError is the error returned when a connection string cannot be
// parsed. Its error text masks recognizable passwords on a best-effort basis,
// but malformed input can be too ambiguous to redact completely.
type ParseConfigError struct {
ConnString string // The connection string that could not be parsed.
ConnString string // The original, unredacted connection string that could not be parsed.
msg string
err error
}
@@ -134,9 +145,11 @@ func NewParseConfigError(conn, msg string, err error) error {
}
func (e *ParseConfigError) Error() string {
// Now that ParseConfigError is public and ConnString is available to the developer, perhaps it would be better only
// return a static string. That would ensure that the error message cannot leak a password. The ConnString field would
// allow access to the original string if desired and Unwrap would allow access to the underlying error.
// redactPW is necessarily best effort: an invalid connection string can be
// too ambiguous to identify every password. Returning only a static string
// would be the way to guarantee that Error cannot leak one. The public
// ConnString field would still allow access to the original string if
// desired, and Unwrap would allow access to the underlying error.
connString := redactPW(e.ConnString)
if e.err == nil {
return fmt.Sprintf("cannot parse `%s`: %s", connString, e.msg)
@@ -227,11 +240,12 @@ func newContextAlreadyDoneError(ctx context.Context) (err error) {
return &errTimeout{&contextAlreadyDoneError{err: ctx.Err()}}
}
// redactPW masks recognizable password fields on a best-effort basis. It
// cannot guarantee redaction when malformed input makes component boundaries
// ambiguous.
func redactPW(connString string) string {
if strings.HasPrefix(connString, "postgres://") || strings.HasPrefix(connString, "postgresql://") {
if u, err := url.Parse(connString); err == nil {
return redactURL(u)
}
return redactURLPassword(connString)
}
quotedKV := regexp.MustCompile(`password='[^']*'`)
connString = quotedKV.ReplaceAllLiteralString(connString, "password=xxxxx")
@@ -242,14 +256,164 @@ func redactPW(connString string) string {
return connString
}
func redactURL(u *url.URL) string {
if u == nil {
return ""
// redactURLPassword masks recognizable password values in a connection URI.
// For a URI that parses cleanly the component boundaries are certain, and
// every password position -- the userinfo password and password/sslpassword
// query values -- is reliably masked with the rest of the string left intact.
// It is also deliberately usable without a successful parse -- the strings
// that reach ParseConfigError are often exactly the ones that failed to parse
// -- but malformed syntax can make component boundaries ambiguous, so for
// such input redaction is best-effort and may over-mask.
//
// For URI shapes it recognizes, it mirrors parseURLSettings structurally
// rather than pattern-matching the raw text: the userinfo password is whatever
// follows the first ':' before the terminating '@' (found with the parser's
// lookahead), and a query value is masked when its percent-decoded key
// canonicalizes to password or sslpassword. This uses the same decoding as the
// parser, so encoded spellings like pass%77ord are caught and the whole
// recognized raw value is masked no matter what bytes it contains.
func redactURLPassword(connString string) string {
const mask = "xxxxx"
var b strings.Builder
b.Grow(len(connString))
p := connString
for _, prefix := range []string{"postgresql://", "postgres://"} {
if rest, ok := strings.CutPrefix(connString, prefix); ok {
b.WriteString(prefix)
p = rest
break
}
}
if _, pwSet := u.User.Password(); pwSet {
u.User = url.UserPassword(u.User.Username(), "xxxxx")
// Userinfo: same lookahead as parseURLSettings.
if i := strings.IndexAny(p, "@/"); i >= 0 && p[i] == '@' {
user, _, hasPassword := strings.Cut(p[:i], ":")
p = p[i+1:]
b.WriteString(user)
if hasPassword {
b.WriteString(":" + mask)
}
b.WriteByte('@')
}
return u.String()
// Nothing after the userinfo is a password position, but a password can
// land there in malformed URIs: an unencoded '/' or '?' in a userinfo
// password turns everything after it into path or query, stranding the
// '@' (postgres://user:pass/word?x=y@host). As a best-effort heuristic,
// while an '@' remains, mask everything shaped like
// ":candidate-credential@" across the whole
// remainder -- before the query is split off, or a stranded '@' inside
// the query would hide the pattern, and greedily up to each '@', so a
// ':' inside the stranded password (user:sec:ret@host) cannot split the
// mask and leak the part before it.
//
// The heuristic must not run when the connection string is structurally
// unambiguous: then nothing can be stranded, a remaining '@' is ordinary
// data (typically in a query value), and the greedy mask would swallow
// the '/' and '?' delimiters -- hiding the query from the password-key
// masking below, so a password=... query parameter would leak. Valid
// URIs must always redact exactly; the heuristic is reserved for
// malformed input, where only best effort is possible.
if strings.IndexByte(p, '@') >= 0 && !uriStructureUnambiguous(connString) {
brokenUserinfo := regexp.MustCompile(`:[^@]+@`)
p = brokenUserinfo.ReplaceAllLiteralString(p, ":xxxxxx@")
}
qi := uriQueryStart(p)
if qi < 0 {
b.WriteString(p)
return b.String()
}
b.WriteString(p[:qi])
query := p[qi+1:]
b.WriteByte('?')
for i, pair := range strings.Split(query, "&") {
if i > 0 {
b.WriteByte('&')
}
rawKey, _, hasValue := strings.Cut(pair, "=")
if !hasValue {
b.WriteString(pair)
continue
}
switch canonicalConnStringKey(uriDecodeLenient(rawKey)) {
case "password", "sslpassword":
b.WriteString(rawKey)
b.WriteByte('=')
b.WriteString(mask)
default:
b.WriteString(pair)
}
}
return b.String()
}
// uriStructureUnambiguous reports whether connString parses as a connection
// URI whose component boundaries are certain, meaning redactURLPassword's
// structural walk is exact and no password bytes can sit outside the two
// positions it masks (the userinfo password and password-keyed query values).
// That requires parseURLSettings to accept the string and every port element
// to be numeric or empty: the parser accepts arbitrary text in the port slot
// (postgres://a@u:sec:ret@h parses with port "sec:ret@h"), so a non-numeric
// port may be a mislaid password and keeps the string in best-effort
// territory.
func uriStructureUnambiguous(connString string) bool {
settings, _, err := parseURLSettings(connString)
if err != nil {
return false
}
for part := range strings.SplitSeq(settings["port"], ",") {
for i := 0; i < len(part); i++ {
if part[i] < '0' || part[i] > '9' {
return false
}
}
}
return true
}
// uriQueryStart returns the index of the '?' that begins the query component
// of p (the post-scheme, post-userinfo part of a connection URI), or -1 if
// there is none. It follows parseURLSettings' structure: '[' at the start of
// a netloc element opens an IPv6 bracket whose contents -- deliberately
// unvalidated -- may contain a literal '?' that is host data, not the query
// delimiter. On an unterminated bracket (the parser errors there) it falls
// back to the first '?' anywhere. With no valid structure to follow,
// over-including text gives the best-effort redactor more candidate pairs to
// inspect.
func uriQueryStart(p string) int {
i := 0
for {
if i < len(p) && p[i] == '[' {
end := strings.IndexByte(p[i:], ']')
if end < 0 {
return strings.IndexByte(p, '?')
}
i += end + 1
}
// Host and port data: everything up to a '/', '?', or ','.
for i < len(p) && p[i] != '/' && p[i] != '?' && p[i] != ',' {
i++
}
if i < len(p) && p[i] == ',' {
i++
continue
}
break
}
if i == len(p) {
return -1
}
if p[i] == '?' {
return i
}
// p[i] == '/': a path follows; the first '?' after it starts the query.
if j := strings.IndexByte(p[i:], '?'); j >= 0 {
return i + j
}
return -1
}
type NotPreferredError struct {
+52
View File
@@ -0,0 +1,52 @@
"""Generate RFC 3454 table A.1 using Python's fixed Unicode 3.2 database.
Run from this directory with: python3 gen_saslprep_unassigned.py
Only the Python standard library is needed; no network access is required.
"""
from pathlib import Path
import stringprep
from unicodedata import ucd_3_2_0
assert ucd_3_2_0.unidata_version == "3.2.0"
def ranges(start, stop):
first = None
for code in range(start, stop):
if stringprep.in_table_a1(chr(code)):
if first is None:
first = code
elif first is not None:
yield first, code - 1
first = None
if first is not None:
yield first, stop - 1
lines = [
"// Code generated by gen_saslprep_unassigned.py; DO NOT EDIT.",
"",
"package pgconn",
"",
'import "unicode"',
"",
"//go:generate python3 gen_saslprep_unassigned.py",
"",
"// saslprepUnassigned is RFC 3454 table A.1: code points unassigned in",
"// Unicode 3.2. This table must not track the Go toolchain's Unicode version.",
"// https://www.rfc-editor.org/rfc/rfc3454#appendix-A.1",
"var saslprepUnassigned = &unicode.RangeTable{",
]
for name, width, start, stop in [
("R16", 16, 0, 0x10000),
("R32", 32, 0x10000, 0x110000),
]:
lines.append(f"\t{name}: []unicode.Range{width}{{")
for first, last in ranges(start, stop):
lines.append(f"\t\t{{0x{first:04x}, 0x{last:04x}, 1}},")
lines.append("\t},")
lines.extend(["}", ""])
Path(__file__).with_name("saslprep_unassigned.go").write_text(
"\n".join(lines), encoding="utf-8"
)
+24 -9
View File
@@ -2,7 +2,9 @@
package bgreader
import (
"errors"
"io"
"net"
"sync"
"github.com/jackc/pgx/v5/internal/iobufpool"
@@ -76,7 +78,18 @@ func (r *BGReader) bgRead() {
*buf = (*buf)[:n]
r.cond.L.Lock()
r.readResults = append(r.readResults, readResult{buf: buf, err: err})
// A timeout belongs to the deadline that was in effect for this read, not to the data stream. It is not buffered
// because a later Read could receive it after the deadline has already been cleared. The background reader stops
// instead and the next Read goes to the underlying reader, which returns a fresh timeout if the deadline is still
// in effect.
switch {
case !isTimeout(err):
r.readResults = append(r.readResults, readResult{buf: buf, err: err})
case n > 0:
r.readResults = append(r.readResults, readResult{buf: buf})
default:
iobufpool.Put(buf)
}
if r.status == StatusStopping || err != nil {
r.status = StatusStopped
keepReading = false
@@ -91,20 +104,22 @@ func (r *BGReader) Read(p []byte) (int, error) {
r.cond.L.Lock()
defer r.cond.L.Unlock()
// Wait for results from the background reader
for len(r.readResults) == 0 && r.status != StatusStopped {
r.cond.Wait()
}
if len(r.readResults) > 0 {
return r.readFromReadResults(p)
}
// There are no unread background read results and the background reader is stopped.
if r.status == StatusStopped {
return r.r.Read(p)
}
return r.r.Read(p)
}
// Wait for results from the background reader
for len(r.readResults) == 0 {
r.cond.Wait()
}
return r.readFromReadResults(p)
func isTimeout(err error) bool {
var netErr net.Error
return errors.As(err, &netErr) && netErr.Timeout()
}
// readBackgroundResults reads a result previously read by the background reader. r.cond.L must be held.
+397
View File
@@ -0,0 +1,397 @@
package pgconn
import (
"errors"
"fmt"
"maps"
"strings"
)
// This file parses PostgreSQL connection URIs using a parser designed to
// exactly match libpq's URI parser behavior (conninfo_uri_parse_options,
// conninfo_uri_parse_params, and conninfo_uri_decode in
// src/interfaces/libpq/fe-connect.c), so that pgx accepts and rejects exactly
// the same URIs as libpq, including libpq's multiple-host extension
// (postgresql://host1:port1,host2:port2/db), which is not valid RFC 3986 syntax.
//
// Deliberate differences from libpq:
//
// - Query parameters that libpq does not recognize are accepted. They become
// runtime parameters or pgx-specific options (e.g. pool_max_conns) instead
// of failing the parse.
// - Error messages avoid quoting the unredacted connection string and mask
// recognizable password fields on a best-effort basis. Invalid connection
// strings can be structurally ambiguous, so password redaction cannot be
// guaranteed for every malformed input. libpq quotes the failing input
// verbatim, which can leak a password into error messages and logs.
// - Literal NUL bytes are rejected. libpq never sees them because C strings
// end at the first NUL; a Go string can carry one into the startup packet,
// where it would act as a protocol delimiter and inject extra parameters.
// parseURLMeta reports provenance facts about a parsed URI that
// ParseConfigWithOptions needs for ConnStringAllowedKeys validation and that
// cannot be recovered from the settings map itself.
type parseURLMeta struct {
// impliedEmptyPortList: the "port" entry is an all-empty list synthesized
// from the host list (postgres://h1,h2 yields port=",") with no port
// bytes supplied by the user. Determined from the raw port syntax, not
// the decoded value: a port of literal spaces (postgres://h: /db)
// decodes to empty but was user-supplied.
impliedEmptyPortList bool
// sawRawSSLKey / sawSSLTrueAlias / sawExplicitSSLModeKey record which
// spellings of the ssl and sslmode query keys appeared anywhere in the
// URI -- including occurrences later superseded under last-occurrence-
// wins. The ssl=true alias rewrite and ordinary repeated-key handling can
// remove those occurrences from the final settings map, so
// ConnStringAllowedKeys cannot fail closed from that map alone; it must see
// every key the user actually wrote.
sawRawSSLKey bool // key "ssl" with a value other than "true"
sawSSLTrueAlias bool // key "ssl" with value "true" (stored as sslmode=require)
sawExplicitSSLModeKey bool // key "sslmode"
}
// parseURLSettings parses a connection URI into a settings map. connString
// must start with "postgres://" or "postgresql://".
//
// Multiple hosts are represented in the returned map the same way libpq
// represents them internally: settings["host"] and settings["port"] are
// comma-separated lists that are positionally aligned, with empty elements
// meaning "use the default". The lists are split in ParseConfigWithOptions.
func parseURLSettings(connString string) (settings map[string]string, meta parseURLMeta, err error) {
settings = make(map[string]string)
if strings.IndexByte(connString, 0) >= 0 {
return nil, meta, errors.New("forbidden NUL byte in connection string")
}
p, ok := strings.CutPrefix(connString, "postgresql://")
if !ok {
p, ok = strings.CutPrefix(connString, "postgres://")
}
if !ok {
return nil, meta, errors.New("invalid URI propagated to internal parser routine")
}
// Look ahead for a possible user credentials designator. Like libpq, only
// a '/' stops the search, so a '@' anywhere before the path -- even inside
// what looks like a query string -- is treated as the userinfo terminator.
if i := strings.IndexAny(p, "@/"); i >= 0 && p[i] == '@' {
user, password, hasPassword := strings.Cut(p[:i], ":")
p = p[i+1:]
if user != "" {
val, err := uriDecode(user, "")
if err != nil {
return nil, meta, err
}
settings["user"] = val
}
if hasPassword && password != "" {
val, err := uriDecode(password, "password")
if err != nil {
return nil, meta, err
}
settings["password"] = val
}
}
// Parse the comma-separated list of netloc[:port] specifications. Hosts
// and ports accumulate into positionally aligned comma-joined lists: every
// separator appends a comma to both, so postgres://h1,h2:5433 yields
// host="h1,h2" port=",5433".
var hostBuf, portBuf strings.Builder
for {
if peekByte(p) == '[' {
// IPv6 address. The bracket contents are not validated, matching libpq.
end := strings.IndexByte(p, ']')
if end < 0 {
return nil, meta, errors.New(`end of string reached when looking for matching "]" in IPv6 host address in URI`)
}
if end == 1 {
return nil, meta, errors.New("IPv6 host address may not be empty in URI")
}
hostBuf.WriteString(p[1:end])
p = p[end+1:]
if c := peekByte(p); c != 0 && c != ':' && c != '/' && c != '?' && c != ',' {
return nil, meta, fmt.Errorf(`unexpected character "%c" at position %d in URI (expected ":" or "/")`, c, len(connString)-len(p)+1)
}
} else {
// DNS-named or IPv4 netloc: everything up to a ':', '/', '?', or ','.
i := strings.IndexAny(p, ":/?,")
if i < 0 {
i = len(p)
}
hostBuf.WriteString(p[:i])
p = p[i:]
}
if peekByte(p) == ':' {
p = p[1:]
i := strings.IndexAny(p, "/?,")
if i < 0 {
i = len(p)
}
portBuf.WriteString(p[:i])
p = p[i:]
}
if peekByte(p) != ',' {
break
}
p = p[1:]
hostBuf.WriteByte(',')
portBuf.WriteByte(',')
}
// The joined lists are percent-decoded as a unit, after joining. This
// means %2C decodes to a comma that later splits like a real separator --
// a host name containing a literal comma is inexpressible, as in libpq.
if hostBuf.Len() > 0 {
hostList, err := uriDecode(hostBuf.String(), "")
if err != nil {
return nil, meta, err
}
settings["host"] = hostList
}
// Like libpq, the port list is stored even when every element is empty
// (postgres://h1,h2 yields port=","). This matters: a connection string
// port shadows PGPORT during settings merge, so with PGPORT=1,2 a
// three-host URI without ports must use the default port for every host,
// not fail the port/host count check. Such an implied all-empty list
// carries no user-supplied port text, which is what
// meta.impliedEmptyPortList reports -- judged on the raw bytes, before
// percent-decoding trims spaces, so a port the user actually typed never
// counts as implied even when it decodes to empty.
if portBuf.Len() > 0 {
meta.impliedEmptyPortList = strings.Trim(portBuf.String(), ",") == ""
portList, err := uriDecode(portBuf.String(), "")
if err != nil {
return nil, meta, err
}
settings["port"] = portList
}
if peekByte(p) == '/' {
p = p[1:]
dbname := p
p = ""
if i := strings.IndexByte(dbname, '?'); i >= 0 {
p = dbname[i:]
dbname = dbname[:i]
}
// Like libpq, an empty path component leaves dbname unset so the
// default stays in effect.
if dbname != "" {
val, err := uriDecode(dbname, "")
if err != nil {
return nil, meta, err
}
settings["database"] = val
}
}
if peekByte(p) == '?' {
// Query parameters land in their own map first: an explicit ?port=
// overrides the netloc-derived port list and is user-supplied port
// text, so it cancels the implied-list exemption even when its value
// is empty.
query := make(map[string]string)
if err := parseURLQueryParams(p[1:], query, &meta); err != nil {
return nil, meta, err
}
if _, ok := query["port"]; ok {
meta.impliedEmptyPortList = false
}
maps.Copy(settings, query)
}
return settings, meta, nil
}
// peekByte returns the first byte of s, or 0 if s is empty. A NUL byte is a
// safe end-of-input sentinel because parseURLSettings rejects literal NULs.
func peekByte(s string) byte {
if len(s) == 0 {
return 0
}
return s[0]
}
// parseURLQueryParams parses the query part of a connection URI into settings,
// mirroring libpq's conninfo_uri_parse_params: '&'-separated pairs, exactly
// one raw '=' per pair, both halves percent-decoded, last occurrence wins. It
// records in meta which spellings of the ssl/sslmode keys it saw (see
// parseURLMeta).
func parseURLQueryParams(params string, settings map[string]string, meta *parseURLMeta) error {
// sslWasLast records whether ssl or sslmode was encountered most recently.
// This matters if the final repeated ssl value is "true": the alias wins
// only when it occurs after the final explicit sslmode.
sslWasLast := false
for params != "" {
pair := params
if i := strings.IndexByte(params, '&'); i >= 0 {
pair = params[:i]
params = params[i+1:]
} else {
params = ""
}
rawKey, rawValue, found := strings.Cut(pair, "=")
if !found {
return fmt.Errorf(`missing key/value separator "=" in URI query parameter: "%s"`, rawKey)
}
if strings.IndexByte(rawValue, '=') >= 0 {
return fmt.Errorf(`extra key/value separator "=" in URI query parameter: "%s"`, rawKey)
}
key, err := uriDecode(rawKey, "")
if err != nil {
return err
}
key = canonicalConnStringKey(key)
secretName := ""
if key == "password" || key == "sslpassword" {
secretName = key
}
value, err := uriDecode(rawValue, secretName)
if err != nil {
return err
}
// Resolve repeated ssl values under their raw key before applying the
// JDBC compatibility alias. Otherwise ssl=true would overwrite an
// independent explicit sslmode that must reappear if a later ssl value
// supersedes the alias. The alias is URI-only and applies only to the
// literal value "true".
switch key {
case "ssl":
sslWasLast = true
if value == "true" {
meta.sawSSLTrueAlias = true
} else {
meta.sawRawSSLKey = true
}
case "sslmode":
sslWasLast = false
meta.sawExplicitSSLModeKey = true
}
settings[key] = value
}
if value, ok := settings["ssl"]; ok && value == "true" {
delete(settings, "ssl")
if sslWasLast {
settings["sslmode"] = "require"
}
}
return nil
}
// uriDecode percent-decodes a URI component with the same rules as libpq's
// conninfo_uri_decode: '%' followed by exactly two case-insensitive hex
// digits, %00 forbidden, leading and trailing ASCII spaces skipped, interior
// spaces rejected. Decoded bytes are emitted raw with no character set
// validation.
//
// If secretName is non-empty, error messages identify that component by name
// instead of quoting its raw value. This prevents the known component's raw
// contents from being copied into the decode error; it does not make the
// separate, best-effort redaction of an invalid connection string complete.
func uriDecode(raw, secretName string) (string, error) {
// The component may be a secret; every error must be built by fail so the
// quote-the-raw-value-or-not redaction decision lives in exactly one place.
fail := func(secretFormat, publicFormat string) (string, error) {
if secretName != "" {
return "", fmt.Errorf(secretFormat, secretName)
}
return "", fmt.Errorf(publicFormat, raw)
}
var b strings.Builder
b.Grow(len(raw))
i := 0
for i < len(raw) && raw[i] == ' ' {
i++
}
for i < len(raw) && raw[i] != ' ' {
if raw[i] != '%' {
b.WriteByte(raw[i])
i++
continue
}
var hi, lo byte
var ok1, ok2 bool
if i+1 < len(raw) {
hi, ok1 = hexDigit(raw[i+1])
}
if i+2 < len(raw) {
lo, ok2 = hexDigit(raw[i+2])
}
if !ok1 || !ok2 {
return fail("invalid percent-encoded token in %s", `invalid percent-encoded token: "%s"`)
}
c := hi<<4 | lo
if c == 0 {
return fail("forbidden value %%00 in percent-encoded value in %s", `forbidden value %%00 in percent-encoded value: "%s"`)
}
b.WriteByte(c)
i += 3
}
for i < len(raw) && raw[i] == ' ' {
i++
}
if i < len(raw) {
return fail("unexpected spaces found in %s, use percent-encoded spaces (%%20) instead", `unexpected spaces found in "%s", use percent-encoded spaces (%%20) instead`)
}
return b.String(), nil
}
// uriDecodeLenient is a non-failing variant of uriDecode used for best-effort
// redaction: valid percent-encodings are decoded, anything uriDecode would
// reject passes through unchanged. Redaction processing itself must not fail,
// and it must see the same key spelling the parser would (pass%77ord decodes
// to password), so encoded password keys are recognized even in connection
// strings that do not parse. This helps recognize keys but cannot make
// redaction complete when malformed input has ambiguous component boundaries.
func uriDecodeLenient(raw string) string {
raw = strings.Trim(raw, " ")
var b strings.Builder
b.Grow(len(raw))
for i := 0; i < len(raw); {
if raw[i] == '%' && i+2 < len(raw) {
hi, ok1 := hexDigit(raw[i+1])
lo, ok2 := hexDigit(raw[i+2])
if ok1 && ok2 {
b.WriteByte(hi<<4 | lo)
i += 3
continue
}
}
b.WriteByte(raw[i])
i++
}
return b.String()
}
func hexDigit(c byte) (byte, bool) {
switch {
case c >= '0' && c <= '9':
return c - '0', true
case c >= 'A' && c <= 'F':
return c - 'A' + 10, true
case c >= 'a' && c <= 'f':
return c - 'a' + 10, true
}
return 0, false
}
+237 -46
View File
@@ -13,6 +13,7 @@ import (
"maps"
"math"
"net"
"slices"
"strconv"
"strings"
"sync"
@@ -146,6 +147,13 @@ func ConnectConfig(ctx context.Context, config *Config) (*PgConn, error) {
panic("config must be created by ParseConfig")
}
// Config may have been modified after ParseConfig. Validate before resolving hosts.
if config.SSLCertMode != "" {
if _, err := parseSSLCertMode(config.SSLCertMode); err != nil {
return nil, &ConnectError{Config: config, err: fmt.Errorf("invalid sslcertmode: %w", err)}
}
}
var allErrors []error
connectConfigs, errs := buildConnectOneConfigs(ctx, config)
@@ -269,6 +277,11 @@ func connectPreferred(ctx context.Context, config *Config, connectOneConfigs []*
allErrors = append(allErrors, err)
var sslCertErr *sslCertModeError
if errors.As(err, &sslCertErr) {
return nil, allErrors
}
var pgErr *PgError
if errors.As(err, &pgErr) {
// pgx will try next host even if libpq does not in certain cases (see #2246)
@@ -340,7 +353,10 @@ func connectOne(ctx context.Context, config *Config, connectConfig *connectOneCo
return nil, newPerDialConnectError("dial error", err)
}
var sslCert *sslCertState
if connectConfig.tlsConfig != nil {
tlsConfig, state := config.prepareTLSConfigForConnect(connectConfig.tlsConfig)
sslCert = state
pgConn.contextWatcher = ctxwatch.NewContextWatcher(&DeadlineContextWatcherHandler{Conn: pgConn.conn})
pgConn.contextWatcher.Watch(ctx)
var (
@@ -348,9 +364,9 @@ func connectOne(ctx context.Context, config *Config, connectConfig *connectOneCo
err error
)
if config.SSLNegotiation == "direct" {
tlsConn = tls.Client(pgConn.conn, connectConfig.tlsConfig)
tlsConn = tls.Client(pgConn.conn, tlsConfig)
} else {
tlsConn, err = startTLS(pgConn.conn, connectConfig.tlsConfig)
tlsConn, err = startTLS(pgConn.conn, tlsConfig)
}
pgConn.contextWatcher.Unwatch() // Always unwatch `netConn` after TLS.
if err != nil {
@@ -392,6 +408,9 @@ func connectOne(ctx context.Context, config *Config, connectConfig *connectOneCo
pgConn.slowWriteTimer.Stop()
pgConn.bgReaderStarted = make(chan struct{})
pgConn.frontend = config.BuildFrontend(pgConn.bgReader, pgConn.conn)
if config.MaxProtocolMessageBodyLen > 0 {
pgConn.frontend.SetMaxBodyLen(config.MaxProtocolMessageBodyLen)
}
startupMsg := pgproto3.StartupMessage{
ProtocolVersion: maxProtocolVersion,
@@ -426,6 +445,12 @@ func connectOne(ctx context.Context, config *Config, connectConfig *connectOneCo
return nil, newPerDialConnectError("require_auth check failed", err)
}
clientFinishedAuth := false
authenticationAccepted := false
channelBound := false
channelBindingFail := func() (*PgConn, error) {
pgConn.conn.Close()
return nil, newPerDialConnectError("channel binding check failed", errors.New("channel binding required but server did not authenticate using channel binding"))
}
for {
msg, err := pgConn.receiveMessage()
@@ -437,15 +462,33 @@ func connectOne(ctx context.Context, config *Config, connectConfig *connectOneCo
return nil, newPerDialConnectError("failed to receive message", err)
}
if config.ChannelBinding == "require" {
switch msg.(type) {
case *pgproto3.AuthenticationCleartextPassword, *pgproto3.AuthenticationMD5Password, *pgproto3.AuthenticationGSS:
// Reject incompatible methods before sending credentials.
return channelBindingFail()
}
}
switch msg := msg.(type) {
case *pgproto3.BackendKeyData:
pgConn.pid = msg.ProcessID
pgConn.secretKey = msg.SecretKey
case *pgproto3.AuthenticationOk:
if config.SSLCertMode == "require" {
if err := sslCert.checkRequired(); err != nil {
pgConn.conn.Close()
return nil, newPerDialConnectError("sslcertmode check failed", err)
}
}
if config.ChannelBinding == "require" && !channelBound {
return channelBindingFail()
}
if requireAuthPolicy.authRequired && !clientFinishedAuth {
return requireAuthFail(requireAuthPolicy.check(authMethodNone))
}
authenticationAccepted = true
case *pgproto3.AuthenticationCleartextPassword:
if err := requireAuthPolicy.check(authMethodPassword); err != nil {
return requireAuthFail(err)
@@ -469,15 +512,12 @@ func connectOne(ctx context.Context, config *Config, connectConfig *connectOneCo
clientFinishedAuth = true
case *pgproto3.AuthenticationSASL:
// Check if OAUTHBEARER is supported
serverSupportsOAuthBearer := false
for _, mech := range msg.AuthMechanisms {
if mech == "OAUTHBEARER" {
serverSupportsOAuthBearer = true
break
}
}
serverSupportsOAuthBearer := slices.Contains(msg.AuthMechanisms, "OAUTHBEARER")
if serverSupportsOAuthBearer && pgConn.config.OAuthTokenProvider != nil {
if config.ChannelBinding == "require" {
return channelBindingFail()
}
if err := requireAuthPolicy.check(authMethodOAuth); err != nil {
return requireAuthFail(err)
}
@@ -486,7 +526,7 @@ func connectOne(ctx context.Context, config *Config, connectConfig *connectOneCo
if err := requireAuthPolicy.check(authMethodSCRAMSHA256); err != nil {
return requireAuthFail(err)
}
err = pgConn.scramAuth(msg.AuthMechanisms)
channelBound, err = pgConn.scramAuth(msg.AuthMechanisms)
}
if err != nil {
pgConn.conn.Close()
@@ -504,6 +544,20 @@ func connectOne(ctx context.Context, config *Config, connectConfig *connectOneCo
}
clientFinishedAuth = true
case *pgproto3.ReadyForQuery:
// Preserve terminal sslcertmode failures even for malformed startup
// sequences that omit AuthenticationOk.
if config.SSLCertMode == "require" {
if err := sslCert.checkRequired(); err != nil {
pgConn.conn.Close()
return nil, newPerDialConnectError("sslcertmode check failed", err)
}
}
// AuthenticationOk must have passed all completion-policy checks before
// exposing the connection to ValidateConnect or the caller.
if !authenticationAccepted {
pgConn.conn.Close()
return nil, newPerDialConnectError("protocol error", errors.New("received ReadyForQuery before AuthenticationOk"))
}
pgConn.status = connStatusIdle
// The connect-phase deadline-only watcher is no longer needed; replace
// it with the application-supplied watcher so subsequent operations
@@ -574,10 +628,10 @@ func (pgConn *PgConn) signalMessage() chan struct{} {
panic("BUG: signalMessage when already in progress")
}
ch := make(chan struct{})
pgConn.bufferingReceive = true
pgConn.bufferingReceiveMux.Lock()
ch := make(chan struct{})
go func() {
pgConn.bufferingReceiveMsg, pgConn.bufferingReceiveErr = pgConn.frontend.Receive()
pgConn.bufferingReceiveMux.Unlock()
@@ -663,7 +717,9 @@ func (pgConn *PgConn) peekMessage() (pgproto3.BackendMessage, error) {
// receiveMessage receives a message without setting up context cancellation
func (pgConn *PgConn) receiveMessage() (pgproto3.BackendMessage, error) {
if pgConn.status == connStatusClosed {
return nil, &connLockError{status: "conn closed"}
// The connection was closed by a failure earlier in this operation, after a request may already have been sent.
// Unlike a lock failure this is not safe to retry.
return nil, &pgconnError{err: ErrConnClosed, safeToRetry: false}
}
msg, err := pgConn.peekMessage()
@@ -680,6 +736,10 @@ func (pgConn *PgConn) receiveMessage() (pgproto3.BackendMessage, error) {
case *pgproto3.ErrorResponse:
err := ErrorResponseToPgError(msg)
if pgConn.config.OnPgError != nil && !pgConn.config.OnPgError(pgConn, err) {
// The callback may have already closed the connection.
if pgConn.status == connStatusClosed {
return nil, err
}
pgConn.status = connStatusClosed
pgConn.conn.Close() // Ignore error as the connection is already broken and there is already an error to return.
close(pgConn.cleanupDone)
@@ -768,11 +828,12 @@ func (pgConn *PgConn) Close(ctx context.Context) error {
}
// asyncClose marks the connection as closed and asynchronously sends a cancel query message and closes the underlying
// connection.
// connection. The cancel query message is not sent if the connection is still starting up, as no query can be running.
func (pgConn *PgConn) asyncClose() {
if pgConn.status == connStatusClosed {
return
}
sendCancelRequest := pgConn.status != connStatusConnecting
pgConn.status = connStatusClosed
go func() {
@@ -784,12 +845,24 @@ func (pgConn *PgConn) asyncClose() {
ctx, cancel := context.WithDeadline(context.Background(), deadline)
defer cancel()
pgConn.CancelRequest(ctx)
if sendCancelRequest {
pgConn.CancelRequest(ctx)
}
pgConn.conn.SetDeadline(deadline)
pgConn.frontend.Send(&pgproto3.Terminate{})
pgConn.flushWithPotentialWriteReadDeadlock()
// Drain any data already in flight from the server (DataRows that were sent before the
// CancelRequest landed, the resulting ErrorResponse, ReadyForQuery, and finally the server's
// own close after it processes Terminate). Closing a TCP socket while unread data remains in
// the kernel receive buffer causes the OS to send RST instead of FIN, which surfaces on the
// server or proxy as "connection reset by peer". The deadline set above bounds how long this
// will block; on timeout we fall through to Close() and accept the abortive close.
//
// See https://github.com/jackc/pgx/issues/2584
io.Copy(io.Discard, pgConn.conn)
}()
}
@@ -969,7 +1042,7 @@ func (pgConn *PgConn) Prepare(ctx context.Context, name, sql string, paramOIDs [
err := pgConn.flushWithPotentialWriteReadDeadlock()
if err != nil {
pgConn.asyncClose()
return nil, err
return nil, normalizeTimeoutError(ctx, err)
}
psd := &StatementDescription{Name: name, SQL: sql}
@@ -1034,7 +1107,7 @@ func (pgConn *PgConn) Deallocate(ctx context.Context, name string) error {
err := pgConn.flushWithPotentialWriteReadDeadlock()
if err != nil {
pgConn.asyncClose()
return err
return normalizeTimeoutError(ctx, err)
}
for {
@@ -1128,11 +1201,13 @@ func (pgConn *PgConn) CancelRequest(ctx context.Context) error {
// cancel connection. The legacy unencrypted path is still used when the primary connection is
// plaintext (e.g. unix sockets or sslmode=disable).
if pgConn.tlsConfig != nil {
// Cancel requests have no AuthenticationOk, so only the prepared TLS config is needed.
tlsConfig, _ := pgConn.config.prepareTLSConfigForConnect(pgConn.tlsConfig)
var tlsCancelConn net.Conn
if pgConn.config.SSLNegotiation == "direct" {
tlsCancelConn = tls.Client(cancelConn, pgConn.tlsConfig)
tlsCancelConn = tls.Client(cancelConn, tlsConfig)
} else {
tlsCancelConn, err = startTLS(cancelConn, pgConn.tlsConfig)
tlsCancelConn, err = startTLS(cancelConn, tlsConfig)
if err != nil {
return fmt.Errorf("tls error on cancel connection: %w", err)
}
@@ -1225,7 +1300,7 @@ func (pgConn *PgConn) Exec(ctx context.Context, sql string) *MultiResultReader {
pgConn.asyncClose()
pgConn.contextWatcher.Unwatch()
multiResult.closed = true
multiResult.err = err
multiResult.err = normalizeTimeoutError(ctx, err)
pgConn.unlock()
return multiResult
}
@@ -1295,7 +1370,9 @@ func (pgConn *PgConn) ExecPrepared(ctx context.Context, stmtName string, paramVa
//
// This differs from [PgConn.ExecPrepared] in that it takes a [*StatementDescription] instead of the prepared statement name.
// Because it has the [*StatementDescription] it can avoid the Describe Portal message that [PgConn.ExecPrepared] must send to get
// the result column descriptions.
// the result column descriptions. However, if the statement description has no fields then a Describe is still sent, as
// an empty Fields may mean the results were not knowable at prepare time, e.g. a FETCH from a cursor that did not exist
// yet.
//
// paramValues are the parameter values. It must be encoded in the format given by paramFormats.
//
@@ -1356,7 +1433,10 @@ func (pgConn *PgConn) execExtendedPrefix(ctx context.Context, paramValues [][]by
}
func (pgConn *PgConn) execExtendedSuffix(result *ResultReader, statementDescription *StatementDescription, resultFormats []int16) {
if statementDescription == nil {
if statementDescription == nil || len(statementDescription.Fields) == 0 {
// The cached field descriptions are missing or empty. Empty field descriptions can occur when the statement's
// result set was not known at prepare time, e.g. a FETCH from a cursor that did not exist yet. Send a Describe
// so the server supplies the actual row description when the statement is executed.
pgConn.frontend.SendDescribe(&pgproto3.Describe{ObjectType: 'P'})
}
pgConn.frontend.SendExecute(&pgproto3.Execute{})
@@ -1365,7 +1445,7 @@ func (pgConn *PgConn) execExtendedSuffix(result *ResultReader, statementDescript
err := pgConn.flushWithPotentialWriteReadDeadlock()
if err != nil {
pgConn.asyncClose()
result.concludeCommand(CommandTag{}, err)
result.concludeCommand(CommandTag{}, normalizeTimeoutError(result.ctx, err))
pgConn.contextWatcher.Unwatch()
result.closed = true
pgConn.unlock()
@@ -1399,7 +1479,7 @@ func (pgConn *PgConn) CopyTo(ctx context.Context, w io.Writer, sql string) (Comm
if err != nil {
pgConn.asyncClose()
pgConn.unlock()
return CommandTag{}, err
return CommandTag{}, normalizeTimeoutError(ctx, err)
}
// Read results
@@ -1456,7 +1536,7 @@ func (pgConn *PgConn) CopyFrom(ctx context.Context, r io.Reader, sql string) (Co
err := pgConn.flushWithPotentialWriteReadDeadlock()
if err != nil {
pgConn.asyncClose()
return CommandTag{}, err
return CommandTag{}, normalizeTimeoutError(ctx, err)
}
// Send copy data
@@ -1542,7 +1622,7 @@ func (pgConn *PgConn) CopyFrom(ctx context.Context, r io.Reader, sql string) (Co
err = pgConn.flushWithPotentialWriteReadDeadlock()
if err != nil {
pgConn.asyncClose()
return CommandTag{}, err
return CommandTag{}, normalizeTimeoutError(ctx, err)
}
// Read results
@@ -1572,10 +1652,15 @@ type MultiResultReader struct {
rr *ResultReader
// Data from when the batch was queued.
// Data from when the batch was queued. There is one entry per command in the batch. Entries are nil for commands
// other than Batch.ExecStatement, which is the only command that does not request a RowDescription from the server.
statementDescriptions []*StatementDescription
resultFormats [][]int16
// Statement data for the command currently being processed. Popped from the queues above at each BindComplete.
currentStatementDescription *StatementDescription
currentResultFormats []int16
closed bool
err error
}
@@ -1619,19 +1704,19 @@ func (mrr *MultiResultReader) NextResult() bool {
for !mrr.closed && mrr.err == nil {
msg, _ := mrr.pgConn.peekMessage()
if _, ok := msg.(*pgproto3.DataRow); ok {
if len(mrr.statementDescriptions) > 0 {
if sd := mrr.currentStatementDescription; sd != nil {
rr := ResultReader{
pgConn: mrr.pgConn,
multiResultReader: mrr,
ctx: mrr.ctx,
}
// This result corresponds to a prepared statement description that was provided when queuing the batch.
sd := mrr.statementDescriptions[0]
mrr.statementDescriptions = mrr.statementDescriptions[1:]
resultFormats := mrr.resultFormats[0]
mrr.resultFormats = mrr.resultFormats[1:]
// This result corresponds to a Batch.ExecStatement command. No RowDescription was requested from the
// server so the field descriptions come from the statement description that was provided when queuing
// the batch.
resultFormats := mrr.currentResultFormats
mrr.currentStatementDescription = nil
mrr.currentResultFormats = nil
sdFields := sd.Fields
rr.fieldDescriptions = rr.pgConn.getFieldDescriptionSlice(len(sdFields))
@@ -1656,7 +1741,24 @@ func (mrr *MultiResultReader) NextResult() bool {
}
switch msg := msg.(type) {
case *pgproto3.BindComplete:
// Every command in a batch begins with a BindComplete. Pop this command's statement data so that the
// following messages are matched with the correct statement description. It must be popped here rather than
// when a DataRow is peeked because a command that returns no rows would otherwise leave its entry in the
// queue, misaligning the statement descriptions for all subsequent commands.
if len(mrr.statementDescriptions) > 0 {
mrr.currentStatementDescription = mrr.statementDescriptions[0]
mrr.statementDescriptions = mrr.statementDescriptions[1:]
mrr.currentResultFormats = mrr.resultFormats[0]
mrr.resultFormats = mrr.resultFormats[1:]
} else {
mrr.currentStatementDescription = nil
mrr.currentResultFormats = nil
}
case *pgproto3.RowDescription:
mrr.currentStatementDescription = nil
mrr.currentResultFormats = nil
mrr.pgConn.resultReader = ResultReader{
pgConn: mrr.pgConn,
multiResultReader: mrr,
@@ -1668,11 +1770,25 @@ func (mrr *MultiResultReader) NextResult() bool {
mrr.rr = &mrr.pgConn.resultReader
return true
case *pgproto3.CommandComplete:
mrr.pgConn.resultReader = ResultReader{
rr := ResultReader{
commandTag: mrr.pgConn.makeCommandTag(msg.CommandTag),
commandConcluded: true,
closed: true,
}
if sd := mrr.currentStatementDescription; sd != nil {
// A Batch.ExecStatement command that returned no rows. Attach the field descriptions from the statement
// description so the result reports its columns the same as a result that was described by the server.
rr.fieldDescriptions = mrr.pgConn.getFieldDescriptionSlice(len(sd.Fields))
err := combineFieldDescriptionsAndResultFormats(rr.fieldDescriptions, sd.Fields, mrr.currentResultFormats)
if err != nil {
rr.err = err
}
mrr.currentStatementDescription = nil
mrr.currentResultFormats = nil
}
mrr.pgConn.resultReader = rr
mrr.rr = &mrr.pgConn.resultReader
return true
case *pgproto3.EmptyQueryResponse:
@@ -1953,6 +2069,11 @@ func (batch *Batch) ExecPrepared(stmtName string, paramValues [][]byte, paramFor
return
}
// The statement data queues must have one entry per command so results can be matched with the correct statement
// description. This command requests a RowDescription from the server so it queues a nil placeholder.
batch.statementDescriptions = append(batch.statementDescriptions, nil)
batch.resultFormats = append(batch.resultFormats, nil)
batch.buf, batch.err = (&pgproto3.Describe{ObjectType: 'P'}).Encode(batch.buf)
if batch.err != nil {
return
@@ -1968,7 +2089,9 @@ func (batch *Batch) ExecPrepared(stmtName string, paramValues [][]byte, paramFor
//
// This differs from ExecPrepared in that it takes a *StatementDescription instead of just the prepared statement name.
// Because it has the *StatementDescription it can avoid the Describe Portal message that ExecPrepared must send to get
// the result column descriptions.
// the result column descriptions. However, if the statement description has no fields then a Describe is still sent, as
// an empty Fields may mean the results were not knowable at prepare time, e.g. a FETCH from a cursor that did not exist
// yet.
func (batch *Batch) ExecStatement(statementDescription *StatementDescription, paramValues [][]byte, paramFormats, resultFormats []int16) {
if batch.err != nil {
return
@@ -1979,6 +2102,16 @@ func (batch *Batch) ExecStatement(statementDescription *StatementDescription, pa
return
}
if len(statementDescription.Fields) == 0 {
// The cached field descriptions are empty, which can occur when the statement's result set was not known at
// prepare time, e.g. a FETCH from a cursor that did not exist yet. Send a Describe so the server supplies the
// actual row description when the statement is executed.
batch.buf, batch.err = (&pgproto3.Describe{ObjectType: 'P'}).Encode(batch.buf)
if batch.err != nil {
return
}
}
batch.statementDescriptions = append(batch.statementDescriptions, statementDescription)
batch.resultFormats = append(batch.resultFormats, resultFormats)
@@ -2242,6 +2375,9 @@ func Construct(hc *HijackedConn) (*PgConn, error) {
pgConn.slowWriteTimer.Stop()
pgConn.bgReaderStarted = make(chan struct{})
pgConn.frontend = hc.Config.BuildFrontend(pgConn.bgReader, pgConn.conn)
if hc.Config.MaxProtocolMessageBodyLen > 0 {
pgConn.frontend.SetMaxBodyLen(hc.Config.MaxProtocolMessageBodyLen)
}
return pgConn, nil
}
@@ -2512,6 +2648,12 @@ func (p *Pipeline) SendQueryStatement(statementDescription *StatementDescription
}
p.conn.frontend.SendBind(&pgproto3.Bind{PreparedStatement: statementDescription.Name, ParameterFormatCodes: paramFormats, Parameters: paramValues, ResultFormatCodes: resultFormats})
if len(statementDescription.Fields) == 0 {
// The cached field descriptions are empty. This can occur when the statement's result set is
// not known at prepare time, e.g. a FETCH from a cursor that did not exist yet. Send a
// Describe so the server supplies the actual row description when the statement is executed.
p.conn.frontend.SendDescribe(&pgproto3.Describe{ObjectType: 'P'})
}
p.conn.frontend.SendExecute(&pgproto3.Execute{})
p.state.PushBackRequestType(pipelineQueryStatement)
p.state.PushBackStatementData(statementDescription, resultFormats)
@@ -2607,22 +2749,29 @@ func (p *Pipeline) getResults() (results any, err error) {
case pipelineNil:
return nil, nil
case pipelinePrepare:
return p.getResultsPrepare()
results, err = p.getResultsPrepare()
case pipelineQueryParams:
return p.getResultsQueryParams()
results, err = p.getResultsQueryParams()
case pipelineQueryPrepared:
return p.getResultsQueryPrepared()
results, err = p.getResultsQueryPrepared()
case pipelineQueryStatement:
return p.getResultsQueryStatement()
results, err = p.getResultsQueryStatement()
case pipelineDeallocate:
return p.getResultsDeallocate()
results, err = p.getResultsDeallocate()
case pipelineSyncRequest:
return p.getResultsSync()
results, err = p.getResultsSync()
case pipelineFlushRequest:
return nil, errors.New("BUG: pipelineFlushRequest should not be in request queue")
default:
return nil, errors.New("BUG: unknown pipeline request type")
}
if err != nil {
// Return an untyped nil instead of an interface containing a typed nil pointer so that callers can compare
// results to nil.
return nil, err
}
return results, nil
}
func (p *Pipeline) getResultsPrepare() (*StatementDescription, error) {
@@ -2699,21 +2848,48 @@ func (p *Pipeline) getResultsQueryPrepared() (*ResultReader, error) {
}
func (p *Pipeline) getResultsQueryStatement() (*ResultReader, error) {
// The statement data must be extracted even if an error occurs. Otherwise, it would still be in the queue and
// subsequent QueryStatement results would be misaligned with their statement descriptions.
sd, resultFormats := p.state.ExtractFrontStatementData()
if sd == nil {
return nil, errors.New("BUG: missing statement description or result formats for QueryStatement")
}
err := p.receiveBindComplete("QueryStatement")
if err != nil {
return nil, err
}
sdFields := sd.Fields
if len(sdFields) == 0 {
// A Describe was sent for this statement (see SendQueryStatement). Read the server-provided
// row description which may include fields that were not known at prepare time.
msg, err := p.receiveMessage()
if err != nil {
return nil, err
}
switch msg := msg.(type) {
case *pgproto3.RowDescription:
sdFields = make([]FieldDescription, len(msg.Fields))
convertRowDescription(sdFields, msg)
case *pgproto3.NoData:
// Statement returns no rows.
case *pgproto3.ErrorResponse:
pgErr := ErrorResponseToPgError(msg)
p.state.HandleError(pgErr)
p.conn.resultReader.closed = true
return nil, pgErr
default:
return nil, p.handleUnexpectedMessage("QueryStatement RowDescription or NoData", msg)
}
}
msg, err := p.receiveMessage()
if err != nil {
return nil, err
}
sd, resultFormats := p.state.ExtractFrontStatementData()
if sd == nil {
return nil, errors.New("BUG: missing statement description or result formats for QueryStatement")
}
sdFields := sd.Fields
fieldDescriptions := p.conn.getFieldDescriptionSlice(len(sdFields))
err = combineFieldDescriptionsAndResultFormats(fieldDescriptions, sdFields, resultFormats)
if err != nil {
@@ -2739,6 +2915,12 @@ func (p *Pipeline) getResultsQueryStatement() (*ResultReader, error) {
fieldDescriptions: fieldDescriptions,
}
return &p.conn.resultReader, nil
case *pgproto3.EmptyQueryResponse:
p.conn.resultReader = ResultReader{
commandConcluded: true,
closed: true,
}
return &p.conn.resultReader, nil
case *pgproto3.ErrorResponse:
pgErr := ErrorResponseToPgError(msg)
p.state.HandleError(pgErr)
@@ -2866,6 +3048,15 @@ func (p *Pipeline) receiveDescribedResultReader(errStr string) (*ResultReader, e
closed: true,
}
return &p.conn.resultReader, nil
// EmptyQueryResponse is returned instead of CommandComplete when the query is empty. e.g. A comment-only query.
case *pgproto3.EmptyQueryResponse:
p.conn.resultReader = ResultReader{
commandConcluded: true,
closed: true,
}
return &p.conn.resultReader, nil
case *pgproto3.ErrorResponse:
pgErr := ErrorResponseToPgError(msg)
p.state.HandleError(pgErr)
+413
View File
@@ -0,0 +1,413 @@
// Code generated by gen_saslprep_unassigned.py; DO NOT EDIT.
package pgconn
import "unicode"
//go:generate python3 gen_saslprep_unassigned.py
// saslprepUnassigned is RFC 3454 table A.1: code points unassigned in
// Unicode 3.2. This table must not track the Go toolchain's Unicode version.
// https://www.rfc-editor.org/rfc/rfc3454#appendix-A.1
var saslprepUnassigned = &unicode.RangeTable{
R16: []unicode.Range16{
{0x0221, 0x0221, 1},
{0x0234, 0x024f, 1},
{0x02ae, 0x02af, 1},
{0x02ef, 0x02ff, 1},
{0x0350, 0x035f, 1},
{0x0370, 0x0373, 1},
{0x0376, 0x0379, 1},
{0x037b, 0x037d, 1},
{0x037f, 0x0383, 1},
{0x038b, 0x038b, 1},
{0x038d, 0x038d, 1},
{0x03a2, 0x03a2, 1},
{0x03cf, 0x03cf, 1},
{0x03f7, 0x03ff, 1},
{0x0487, 0x0487, 1},
{0x04cf, 0x04cf, 1},
{0x04f6, 0x04f7, 1},
{0x04fa, 0x04ff, 1},
{0x0510, 0x0530, 1},
{0x0557, 0x0558, 1},
{0x0560, 0x0560, 1},
{0x0588, 0x0588, 1},
{0x058b, 0x0590, 1},
{0x05a2, 0x05a2, 1},
{0x05ba, 0x05ba, 1},
{0x05c5, 0x05cf, 1},
{0x05eb, 0x05ef, 1},
{0x05f5, 0x060b, 1},
{0x060d, 0x061a, 1},
{0x061c, 0x061e, 1},
{0x0620, 0x0620, 1},
{0x063b, 0x063f, 1},
{0x0656, 0x065f, 1},
{0x06ee, 0x06ef, 1},
{0x06ff, 0x06ff, 1},
{0x070e, 0x070e, 1},
{0x072d, 0x072f, 1},
{0x074b, 0x077f, 1},
{0x07b2, 0x0900, 1},
{0x0904, 0x0904, 1},
{0x093a, 0x093b, 1},
{0x094e, 0x094f, 1},
{0x0955, 0x0957, 1},
{0x0971, 0x0980, 1},
{0x0984, 0x0984, 1},
{0x098d, 0x098e, 1},
{0x0991, 0x0992, 1},
{0x09a9, 0x09a9, 1},
{0x09b1, 0x09b1, 1},
{0x09b3, 0x09b5, 1},
{0x09ba, 0x09bb, 1},
{0x09bd, 0x09bd, 1},
{0x09c5, 0x09c6, 1},
{0x09c9, 0x09ca, 1},
{0x09ce, 0x09d6, 1},
{0x09d8, 0x09db, 1},
{0x09de, 0x09de, 1},
{0x09e4, 0x09e5, 1},
{0x09fb, 0x0a01, 1},
{0x0a03, 0x0a04, 1},
{0x0a0b, 0x0a0e, 1},
{0x0a11, 0x0a12, 1},
{0x0a29, 0x0a29, 1},
{0x0a31, 0x0a31, 1},
{0x0a34, 0x0a34, 1},
{0x0a37, 0x0a37, 1},
{0x0a3a, 0x0a3b, 1},
{0x0a3d, 0x0a3d, 1},
{0x0a43, 0x0a46, 1},
{0x0a49, 0x0a4a, 1},
{0x0a4e, 0x0a58, 1},
{0x0a5d, 0x0a5d, 1},
{0x0a5f, 0x0a65, 1},
{0x0a75, 0x0a80, 1},
{0x0a84, 0x0a84, 1},
{0x0a8c, 0x0a8c, 1},
{0x0a8e, 0x0a8e, 1},
{0x0a92, 0x0a92, 1},
{0x0aa9, 0x0aa9, 1},
{0x0ab1, 0x0ab1, 1},
{0x0ab4, 0x0ab4, 1},
{0x0aba, 0x0abb, 1},
{0x0ac6, 0x0ac6, 1},
{0x0aca, 0x0aca, 1},
{0x0ace, 0x0acf, 1},
{0x0ad1, 0x0adf, 1},
{0x0ae1, 0x0ae5, 1},
{0x0af0, 0x0b00, 1},
{0x0b04, 0x0b04, 1},
{0x0b0d, 0x0b0e, 1},
{0x0b11, 0x0b12, 1},
{0x0b29, 0x0b29, 1},
{0x0b31, 0x0b31, 1},
{0x0b34, 0x0b35, 1},
{0x0b3a, 0x0b3b, 1},
{0x0b44, 0x0b46, 1},
{0x0b49, 0x0b4a, 1},
{0x0b4e, 0x0b55, 1},
{0x0b58, 0x0b5b, 1},
{0x0b5e, 0x0b5e, 1},
{0x0b62, 0x0b65, 1},
{0x0b71, 0x0b81, 1},
{0x0b84, 0x0b84, 1},
{0x0b8b, 0x0b8d, 1},
{0x0b91, 0x0b91, 1},
{0x0b96, 0x0b98, 1},
{0x0b9b, 0x0b9b, 1},
{0x0b9d, 0x0b9d, 1},
{0x0ba0, 0x0ba2, 1},
{0x0ba5, 0x0ba7, 1},
{0x0bab, 0x0bad, 1},
{0x0bb6, 0x0bb6, 1},
{0x0bba, 0x0bbd, 1},
{0x0bc3, 0x0bc5, 1},
{0x0bc9, 0x0bc9, 1},
{0x0bce, 0x0bd6, 1},
{0x0bd8, 0x0be6, 1},
{0x0bf3, 0x0c00, 1},
{0x0c04, 0x0c04, 1},
{0x0c0d, 0x0c0d, 1},
{0x0c11, 0x0c11, 1},
{0x0c29, 0x0c29, 1},
{0x0c34, 0x0c34, 1},
{0x0c3a, 0x0c3d, 1},
{0x0c45, 0x0c45, 1},
{0x0c49, 0x0c49, 1},
{0x0c4e, 0x0c54, 1},
{0x0c57, 0x0c5f, 1},
{0x0c62, 0x0c65, 1},
{0x0c70, 0x0c81, 1},
{0x0c84, 0x0c84, 1},
{0x0c8d, 0x0c8d, 1},
{0x0c91, 0x0c91, 1},
{0x0ca9, 0x0ca9, 1},
{0x0cb4, 0x0cb4, 1},
{0x0cba, 0x0cbd, 1},
{0x0cc5, 0x0cc5, 1},
{0x0cc9, 0x0cc9, 1},
{0x0cce, 0x0cd4, 1},
{0x0cd7, 0x0cdd, 1},
{0x0cdf, 0x0cdf, 1},
{0x0ce2, 0x0ce5, 1},
{0x0cf0, 0x0d01, 1},
{0x0d04, 0x0d04, 1},
{0x0d0d, 0x0d0d, 1},
{0x0d11, 0x0d11, 1},
{0x0d29, 0x0d29, 1},
{0x0d3a, 0x0d3d, 1},
{0x0d44, 0x0d45, 1},
{0x0d49, 0x0d49, 1},
{0x0d4e, 0x0d56, 1},
{0x0d58, 0x0d5f, 1},
{0x0d62, 0x0d65, 1},
{0x0d70, 0x0d81, 1},
{0x0d84, 0x0d84, 1},
{0x0d97, 0x0d99, 1},
{0x0db2, 0x0db2, 1},
{0x0dbc, 0x0dbc, 1},
{0x0dbe, 0x0dbf, 1},
{0x0dc7, 0x0dc9, 1},
{0x0dcb, 0x0dce, 1},
{0x0dd5, 0x0dd5, 1},
{0x0dd7, 0x0dd7, 1},
{0x0de0, 0x0df1, 1},
{0x0df5, 0x0e00, 1},
{0x0e3b, 0x0e3e, 1},
{0x0e5c, 0x0e80, 1},
{0x0e83, 0x0e83, 1},
{0x0e85, 0x0e86, 1},
{0x0e89, 0x0e89, 1},
{0x0e8b, 0x0e8c, 1},
{0x0e8e, 0x0e93, 1},
{0x0e98, 0x0e98, 1},
{0x0ea0, 0x0ea0, 1},
{0x0ea4, 0x0ea4, 1},
{0x0ea6, 0x0ea6, 1},
{0x0ea8, 0x0ea9, 1},
{0x0eac, 0x0eac, 1},
{0x0eba, 0x0eba, 1},
{0x0ebe, 0x0ebf, 1},
{0x0ec5, 0x0ec5, 1},
{0x0ec7, 0x0ec7, 1},
{0x0ece, 0x0ecf, 1},
{0x0eda, 0x0edb, 1},
{0x0ede, 0x0eff, 1},
{0x0f48, 0x0f48, 1},
{0x0f6b, 0x0f70, 1},
{0x0f8c, 0x0f8f, 1},
{0x0f98, 0x0f98, 1},
{0x0fbd, 0x0fbd, 1},
{0x0fcd, 0x0fce, 1},
{0x0fd0, 0x0fff, 1},
{0x1022, 0x1022, 1},
{0x1028, 0x1028, 1},
{0x102b, 0x102b, 1},
{0x1033, 0x1035, 1},
{0x103a, 0x103f, 1},
{0x105a, 0x109f, 1},
{0x10c6, 0x10cf, 1},
{0x10f9, 0x10fa, 1},
{0x10fc, 0x10ff, 1},
{0x115a, 0x115e, 1},
{0x11a3, 0x11a7, 1},
{0x11fa, 0x11ff, 1},
{0x1207, 0x1207, 1},
{0x1247, 0x1247, 1},
{0x1249, 0x1249, 1},
{0x124e, 0x124f, 1},
{0x1257, 0x1257, 1},
{0x1259, 0x1259, 1},
{0x125e, 0x125f, 1},
{0x1287, 0x1287, 1},
{0x1289, 0x1289, 1},
{0x128e, 0x128f, 1},
{0x12af, 0x12af, 1},
{0x12b1, 0x12b1, 1},
{0x12b6, 0x12b7, 1},
{0x12bf, 0x12bf, 1},
{0x12c1, 0x12c1, 1},
{0x12c6, 0x12c7, 1},
{0x12cf, 0x12cf, 1},
{0x12d7, 0x12d7, 1},
{0x12ef, 0x12ef, 1},
{0x130f, 0x130f, 1},
{0x1311, 0x1311, 1},
{0x1316, 0x1317, 1},
{0x131f, 0x131f, 1},
{0x1347, 0x1347, 1},
{0x135b, 0x1360, 1},
{0x137d, 0x139f, 1},
{0x13f5, 0x1400, 1},
{0x1677, 0x167f, 1},
{0x169d, 0x169f, 1},
{0x16f1, 0x16ff, 1},
{0x170d, 0x170d, 1},
{0x1715, 0x171f, 1},
{0x1737, 0x173f, 1},
{0x1754, 0x175f, 1},
{0x176d, 0x176d, 1},
{0x1771, 0x1771, 1},
{0x1774, 0x177f, 1},
{0x17dd, 0x17df, 1},
{0x17ea, 0x17ff, 1},
{0x180f, 0x180f, 1},
{0x181a, 0x181f, 1},
{0x1878, 0x187f, 1},
{0x18aa, 0x1dff, 1},
{0x1e9c, 0x1e9f, 1},
{0x1efa, 0x1eff, 1},
{0x1f16, 0x1f17, 1},
{0x1f1e, 0x1f1f, 1},
{0x1f46, 0x1f47, 1},
{0x1f4e, 0x1f4f, 1},
{0x1f58, 0x1f58, 1},
{0x1f5a, 0x1f5a, 1},
{0x1f5c, 0x1f5c, 1},
{0x1f5e, 0x1f5e, 1},
{0x1f7e, 0x1f7f, 1},
{0x1fb5, 0x1fb5, 1},
{0x1fc5, 0x1fc5, 1},
{0x1fd4, 0x1fd5, 1},
{0x1fdc, 0x1fdc, 1},
{0x1ff0, 0x1ff1, 1},
{0x1ff5, 0x1ff5, 1},
{0x1fff, 0x1fff, 1},
{0x2053, 0x2056, 1},
{0x2058, 0x205e, 1},
{0x2064, 0x2069, 1},
{0x2072, 0x2073, 1},
{0x208f, 0x209f, 1},
{0x20b2, 0x20cf, 1},
{0x20eb, 0x20ff, 1},
{0x213b, 0x213c, 1},
{0x214c, 0x2152, 1},
{0x2184, 0x218f, 1},
{0x23cf, 0x23ff, 1},
{0x2427, 0x243f, 1},
{0x244b, 0x245f, 1},
{0x24ff, 0x24ff, 1},
{0x2614, 0x2615, 1},
{0x2618, 0x2618, 1},
{0x267e, 0x267f, 1},
{0x268a, 0x2700, 1},
{0x2705, 0x2705, 1},
{0x270a, 0x270b, 1},
{0x2728, 0x2728, 1},
{0x274c, 0x274c, 1},
{0x274e, 0x274e, 1},
{0x2753, 0x2755, 1},
{0x2757, 0x2757, 1},
{0x275f, 0x2760, 1},
{0x2795, 0x2797, 1},
{0x27b0, 0x27b0, 1},
{0x27bf, 0x27cf, 1},
{0x27ec, 0x27ef, 1},
{0x2b00, 0x2e7f, 1},
{0x2e9a, 0x2e9a, 1},
{0x2ef4, 0x2eff, 1},
{0x2fd6, 0x2fef, 1},
{0x2ffc, 0x2fff, 1},
{0x3040, 0x3040, 1},
{0x3097, 0x3098, 1},
{0x3100, 0x3104, 1},
{0x312d, 0x3130, 1},
{0x318f, 0x318f, 1},
{0x31b8, 0x31ef, 1},
{0x321d, 0x321f, 1},
{0x3244, 0x3250, 1},
{0x327c, 0x327e, 1},
{0x32cc, 0x32cf, 1},
{0x32ff, 0x32ff, 1},
{0x3377, 0x337a, 1},
{0x33de, 0x33df, 1},
{0x33ff, 0x33ff, 1},
{0x4db6, 0x4dff, 1},
{0x9fa6, 0x9fff, 1},
{0xa48d, 0xa48f, 1},
{0xa4c7, 0xabff, 1},
{0xd7a4, 0xd7ff, 1},
{0xfa2e, 0xfa2f, 1},
{0xfa6b, 0xfaff, 1},
{0xfb07, 0xfb12, 1},
{0xfb18, 0xfb1c, 1},
{0xfb37, 0xfb37, 1},
{0xfb3d, 0xfb3d, 1},
{0xfb3f, 0xfb3f, 1},
{0xfb42, 0xfb42, 1},
{0xfb45, 0xfb45, 1},
{0xfbb2, 0xfbd2, 1},
{0xfd40, 0xfd4f, 1},
{0xfd90, 0xfd91, 1},
{0xfdc8, 0xfdcf, 1},
{0xfdfd, 0xfdff, 1},
{0xfe10, 0xfe1f, 1},
{0xfe24, 0xfe2f, 1},
{0xfe47, 0xfe48, 1},
{0xfe53, 0xfe53, 1},
{0xfe67, 0xfe67, 1},
{0xfe6c, 0xfe6f, 1},
{0xfe75, 0xfe75, 1},
{0xfefd, 0xfefe, 1},
{0xff00, 0xff00, 1},
{0xffbf, 0xffc1, 1},
{0xffc8, 0xffc9, 1},
{0xffd0, 0xffd1, 1},
{0xffd8, 0xffd9, 1},
{0xffdd, 0xffdf, 1},
{0xffe7, 0xffe7, 1},
{0xffef, 0xfff8, 1},
},
R32: []unicode.Range32{
{0x10000, 0x102ff, 1},
{0x1031f, 0x1031f, 1},
{0x10324, 0x1032f, 1},
{0x1034b, 0x103ff, 1},
{0x10426, 0x10427, 1},
{0x1044e, 0x1cfff, 1},
{0x1d0f6, 0x1d0ff, 1},
{0x1d127, 0x1d129, 1},
{0x1d1de, 0x1d3ff, 1},
{0x1d455, 0x1d455, 1},
{0x1d49d, 0x1d49d, 1},
{0x1d4a0, 0x1d4a1, 1},
{0x1d4a3, 0x1d4a4, 1},
{0x1d4a7, 0x1d4a8, 1},
{0x1d4ad, 0x1d4ad, 1},
{0x1d4ba, 0x1d4ba, 1},
{0x1d4bc, 0x1d4bc, 1},
{0x1d4c1, 0x1d4c1, 1},
{0x1d4c4, 0x1d4c4, 1},
{0x1d506, 0x1d506, 1},
{0x1d50b, 0x1d50c, 1},
{0x1d515, 0x1d515, 1},
{0x1d51d, 0x1d51d, 1},
{0x1d53a, 0x1d53a, 1},
{0x1d53f, 0x1d53f, 1},
{0x1d545, 0x1d545, 1},
{0x1d547, 0x1d549, 1},
{0x1d551, 0x1d551, 1},
{0x1d6a4, 0x1d6a7, 1},
{0x1d7ca, 0x1d7cd, 1},
{0x1d800, 0x1fffd, 1},
{0x2a6d7, 0x2f7ff, 1},
{0x2fa1e, 0x2fffd, 1},
{0x30000, 0x3fffd, 1},
{0x40000, 0x4fffd, 1},
{0x50000, 0x5fffd, 1},
{0x60000, 0x6fffd, 1},
{0x70000, 0x7fffd, 1},
{0x80000, 0x8fffd, 1},
{0x90000, 0x9fffd, 1},
{0xa0000, 0xafffd, 1},
{0xb0000, 0xbfffd, 1},
{0xc0000, 0xcfffd, 1},
{0xd0000, 0xdfffd, 1},
{0xe0000, 0xe0000, 1},
{0xe0002, 0xe001f, 1},
{0xe0080, 0xefffd, 1},
},
}