cockroach: Index | Files | Directories

package pgwire

import ""


Package Files

auth.go auth_methods.go command_result.go conn.go hba_conf.go server.go types.go write_buffer.go


const (
    // ErrSSLRequired is returned when a client attempts to connect to a
    // secure server in cleartext.
    ErrSSLRequired = "node is running secure mode, SSL connection required"

    // ErrDrainingNewConn is returned when a client attempts to connect to a server
    // which is not accepting client connections.
    ErrDrainingNewConn = "server is not accepting clients"
    // ErrDrainingExistingConn is returned when a connection is shut down because
    // the server is draining.
    ErrDrainingExistingConn = "server is shutting down"


var (
    MetaConns = metric.Metadata{
        Name:        "sql.conns",
        Help:        "Number of active sql connections",
        Measurement: "Connections",
        Unit:        metric.Unit_COUNT,
    MetaNewConns = metric.Metadata{
        Name:        "sql.new_conns",
        Help:        "Counter of the number of sql connections created",
        Measurement: "Connections",
        Unit:        metric.Unit_COUNT,
    MetaBytesIn = metric.Metadata{
        Name:        "sql.bytesin",
        Help:        "Number of sql bytes received",
        Measurement: "SQL Bytes",
        Unit:        metric.Unit_BYTES,
    MetaBytesOut = metric.Metadata{
        Name:        "sql.bytesout",
        Help:        "Number of sql bytes sent",
        Measurement: "SQL Bytes",
        Unit:        metric.Unit_BYTES,

Fully-qualified names for metrics.

var DefaultHBAConfig = func() *hba.Conf {
    conf, err := ParseAndNormalize("" /* 131 byte string literal not displayed */,
    if err != nil {
    return conf

DefaultHBAConfig is used when the stored HBA configuration string is empty or invalid.

func Match Uses

func Match(rd io.Reader) bool

Match returns true if rd appears to be a Postgres connection.

func ParseAndNormalize Uses

func ParseAndNormalize(val string) (*hba.Conf, error)

ParseAndNormalize calls hba.ParseAndNormalize and also ensures the configuration starts with a rule that authenticates the root user with client certificates.

This prevents users from shooting themselves in the foot and making root not able to login, thus disallowing anyone from fixing the HBA configuration.

func RegisterAuthMethod Uses

func RegisterAuthMethod(
    method string,
    fn AuthMethod,
    minReqVersion clusterversion.VersionKey,
    validConnTypes hba.ConnType,
    checkEntry CheckHBAEntry,

RegisterAuthMethod registers an AuthMethod for pgwire authentication and for use in HBA configuration.

The minReqVersion is checked upon configuration to verify whether the current active cluster version is at least the version specified.

The validConnTypes is checked during rule matching when accepting connections: if the connection type is not accepted by the auth method, authentication is refused upfront. For example, the "cert" method requires SSL; if a rule specifies "host .... cert" and the client connects without SSL, the authentication is refused. (To express "cert on SSL, password on non-SSL", the HBA conf can list 'hostssl ... cert; hostnossl .... password' instead.)

The checkEntry method, if provided, is called upon configuration the cluster setting in the SQL client which attempts to change the configuration. It can block the configuration if e.g. the syntax is invalid.

type AuthConn Uses

type AuthConn interface {
    // SendAuthRequest send a request for authentication information. After
    // calling this, the authenticator needs to call GetPwdData() quickly, as the
    // connection's goroutine will be blocked on providing us the requested data.
    SendAuthRequest(authType int32, data []byte) error
    // GetPwdData returns authentication info that was previously requested with
    // SendAuthRequest. The call blocks until such data is available.
    // An error is returned if the client connection dropped or if the client
    // didn't respect the protocol. After an error has been returned, GetPwdData()
    // cannot be called any more.
    GetPwdData() ([]byte, error)
    // AuthOK declares that authentication succeeded and provides a
    // unqualifiedIntSizer, to be returned by authenticator.authResult(). Future
    // authenticator.sendPwdData() calls fail.
    // AuthFail declares that authentication has failed and provides an error to
    // be returned by authenticator.authResult(). Future
    // authenticator.sendPwdData() calls fail. The error has already been written
    // to the client connection.
    AuthFail(err error)
    // Logf logs a message on the authentication log, if auth logs
    // are enabled.
    Logf(ctx context.Context, format string, args ...interface{})

AuthConn is the interface used by the authenticator for interacting with the pgwire connection.

type AuthMethod Uses

type AuthMethod func(
    ctx context.Context,
    c AuthConn,
    tlsState tls.ConnectionState,
    pwRetrieveFn PasswordRetrievalFn,
    pwValidUntilFn PasswordValidUntilFn,
    execCfg *sql.ExecutorConfig,
    entry *hba.Entry,
) (security.UserAuthHook, error)

AuthMethod defines a method for authentication of a connection.

type CheckHBAEntry Uses

type CheckHBAEntry func(hba.Entry) error

CheckHBAEntry defines a method for validating an hba Entry upon configuration of the cluster setting by a SQL client.

type PasswordRetrievalFn Uses

type PasswordRetrievalFn = func(context.Context) ([]byte, error)

PasswordRetrievalFn defines a method to retrieve the hashed password for the user logging in.

type PasswordValidUntilFn Uses

type PasswordValidUntilFn = func(context.Context) (*tree.DTimestamp, error)

PasswordValidUntilFn defines a method to retrieve the expiration time of the user's password.

type Server Uses

type Server struct {
    AmbientCtx log.AmbientContext

    SQLServer *sql.Server
    // contains filtered or unexported fields

Server implements the server side of the PostgreSQL wire protocol.

func MakeServer Uses

func MakeServer(
    ambientCtx log.AmbientContext,
    cfg *base.Config,
    st *cluster.Settings,
    sqlMemMetrics sql.MemoryMetrics,
    parentMemoryMonitor *mon.BytesMonitor,
    histogramWindow time.Duration,
    executorConfig *sql.ExecutorConfig,
) *Server

MakeServer creates a Server.

Start() needs to be called on the Server so it begins processing.

func (*Server) Drain Uses

func (s *Server) Drain(drainWait time.Duration, reporter func(int, string)) error

Drain prevents new connections from being served and waits for drainWait for open connections to terminate before canceling them. An error will be returned when connections that have been canceled have not responded to this cancellation and closed themselves in time. The server will remain in draining state, though open connections may continue to exist. The RFC on drain modes has more information regarding the specifics of what will happen to connections in different states:

The reporter callback, if non-nil, is called on a best effort basis to report work that needed to be done and which may or may not have been done by the time this call returns. See the explanation in pkg/server/drain.go for details.

func (*Server) GetAuthenticationConfiguration Uses

func (s *Server) GetAuthenticationConfiguration() *hba.Conf

GetAuthenticationConfiguration retrieves the current applicable authentication configuration.

This is guaranteed to return a valid configuration. Additionally, the various setters for the configuration also pass through ParseAndNormalize(), whereby an entry is always present at the start, to enable root to log in with a valid client cert.

The data returned by this method is also observable via the debug endpoint /debug/hba_conf.

func (*Server) HBADebugFn Uses

func (s *Server) HBADebugFn() http.HandlerFunc

HBADebugFn exposes the computed HBA configuration via the debug interface, for inspection by tests.

func (*Server) IsDraining Uses

func (s *Server) IsDraining() bool

IsDraining returns true if the server is not currently accepting connections.

func (*Server) Metrics Uses

func (s *Server) Metrics() (res []interface{})

Metrics returns the set of metrics structs.

func (*Server) ServeConn Uses

func (s *Server) ServeConn(ctx context.Context, conn net.Conn, socketType SocketType) error

ServeConn serves a single connection, driving the handshake process and delegating to the appropriate connection type.

The socketType argument is an optimization to avoid a string compare on conn.LocalAddr().Network(). When the socket type is unix datagram (local filesystem), SSL negotiation is disabled even when the server is running securely with certificates. This has the effect of forcing password auth, also in a way compatible with postgres.

An error is returned if the initial handshake of the connection fails.

func (*Server) Start Uses

func (s *Server) Start(ctx context.Context, stopper *stop.Stopper)

Start makes the Server ready for serving connections.

func (*Server) TestingEnableConnAuthLogging Uses

func (s *Server) TestingEnableConnAuthLogging()

TestingEnableConnAuthLogging is exported for use in tests.

func (*Server) Undrain Uses

func (s *Server) Undrain()

Undrain switches the server back to the normal mode of operation in which connections are accepted.

type ServerMetrics Uses

type ServerMetrics struct {
    BytesInCount   *metric.Counter
    BytesOutCount  *metric.Counter
    Conns          *metric.Gauge
    NewConns       *metric.Counter
    ConnMemMetrics sql.MemoryMetrics
    SQLMemMetrics  sql.MemoryMetrics

ServerMetrics is the set of metrics for the pgwire server.

type SocketType Uses

type SocketType bool

SocketType indicates the connection type. This is an optimization to prevent a comparison against conn.LocalAddr().Network().

const (
    // SocketTCP is used for TCP sockets. The standard.
    SocketTCP SocketType = true
    // SocketUnix is used for unix datagram sockets.
    SocketUnix SocketType = false


hbaPackage hba implements an hba.conf parser.
pgcodePackage pgcode defines the PostgreSQL 5-character support codes used throughout the CockroachDB source tree.
pgwirebasePackage pgwirebase contains type definitions and very basic protocol structures to be used by both the pgwire package and by others (particularly by the sql package).

Package pgwire imports 55 packages (graph) and is imported by 43 packages. Updated 2020-08-13. Refresh now. Tools for package owners.