server

package
v1.14.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 25, 2026 License: MIT Imports: 29 Imported by: 21

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrAccessDenied           = errors.New("access denied")
	ErrAccessDeniedNoPassword = fmt.Errorf("%w without password", ErrAccessDenied)
)

Functions

func NewServerTLSConfig

func NewServerTLSConfig(caPem, certPem, keyPem []byte, authType tls.ClientAuthType) *tls.Config

NewServerTLSConfig: generate TLS config for server side controlling the security level by authType

Types

type AuthenticationHandler added in v1.14.0

type AuthenticationHandler interface {
	// GetCredential returns the user credential (supports multiple valid passwords per user).
	// Implementations must be safe for concurrent use.
	GetCredential(username string) (credential Credential, found bool, err error)

	// OnAuthSuccess is called after successful authentication, before the OK packet.
	// Return an error to reject the connection (error will be sent to client instead of OK).
	// Return nil to proceed with sending the OK packet.
	OnAuthSuccess(conn *Conn) error

	// OnAuthFailure is called after authentication fails, before the error packet.
	// This is informational only - the connection will be closed regardless.
	OnAuthFailure(conn *Conn, err error)
}

AuthenticationHandler provides user credentials and authentication lifecycle hooks.

Important Note

if the password in a third-party auth handler could be updated at runtime, we have to invalidate the caching for 'caching_sha2_password' by calling 'func (s *Server)InvalidateCache(string, string)'.

type AuthenticationProvider added in v1.14.0

type AuthenticationProvider interface {
	Authenticate(c *Conn, authPluginName string, clientAuthData []byte) error
	Validate(authPluginName string) bool
}

type Conn

type Conn struct {
	*packet.Conn
	// contains filtered or unexported fields
}

Conn acts like a MySQL server connection, you can use MySQL client to communicate with it.

func NewConn deprecated

func NewConn(conn net.Conn, user string, password string, h Handler) (*Conn, error)

NewConn: create connection with default server settings

Deprecated: Use Server.NewConn instead.

func NewCustomizedConn deprecated

func NewCustomizedConn(conn net.Conn, serverConf *Server, authHandler AuthenticationHandler, h Handler) (*Conn, error)

NewCustomizedConn: create connection with customized server settings

Deprecated: Use Server.NewCustomizedConn instead.

func (*Conn) Attributes added in v1.5.0

func (c *Conn) Attributes() map[string]string

Attributes returns the connection attributes. Note that this is only sent to the server if CLIENT_CONNECT_ATTRS is set.

func (*Conn) Capability added in v1.4.0

func (c *Conn) Capability() uint32

func (*Conn) Charset added in v1.4.0

func (c *Conn) Charset() uint8

func (*Conn) ClearInTransaction

func (c *Conn) ClearInTransaction()

func (*Conn) Close

func (c *Conn) Close()

func (*Conn) Closed

func (c *Conn) Closed() bool

func (*Conn) ConnectionID

func (c *Conn) ConnectionID() uint32

func (*Conn) GetUser

func (c *Conn) GetUser() string

func (*Conn) HandleCommand

func (c *Conn) HandleCommand() error

HandleCommand is handling commands received by the server https://dev.mysql.com/doc/dev/mysql-server/latest/page_protocol_command_phase.html

func (*Conn) HasCapability added in v1.4.0

func (c *Conn) HasCapability(cap uint32) bool

func (*Conn) HasStatus added in v1.4.0

func (c *Conn) HasStatus(status uint16) bool

func (*Conn) IsAutoCommit

func (c *Conn) IsAutoCommit() bool

func (*Conn) IsInTransaction

func (c *Conn) IsInTransaction() bool

func (*Conn) SetCapability added in v1.4.0

func (c *Conn) SetCapability(cap uint32)

func (*Conn) SetInTransaction

func (c *Conn) SetInTransaction()

func (*Conn) SetStatus added in v1.4.0

func (c *Conn) SetStatus(status uint16)

func (*Conn) SetWarnings added in v1.4.0

func (c *Conn) SetWarnings(warnings uint16)

func (*Conn) UnsetCapability added in v1.4.0

func (c *Conn) UnsetCapability(cap uint32)

func (*Conn) UnsetStatus added in v1.4.0

func (c *Conn) UnsetStatus(status uint16)

func (*Conn) WriteValue added in v1.4.0

func (c *Conn) WriteValue(value any) error

type Credential added in v1.14.0

type Credential struct {
	Passwords      []string
	AuthPluginName string
}

Credential holds authentication settings for a user. Passwords contains all valid raw passwords for the user. They are hashed on demand during comparison. If empty password authentication is allowed, Passwords must contain an empty string (e.g., []string{""}) rather than being a zero-length slice. A zero-length slice means no valid passwords are configured.

type DefaultAuthenticationProvider added in v1.14.0

type DefaultAuthenticationProvider struct{}

func (*DefaultAuthenticationProvider) Authenticate added in v1.14.0

func (d *DefaultAuthenticationProvider) Authenticate(c *Conn, authPluginName string, clientAuthData []byte) error

func (*DefaultAuthenticationProvider) Validate added in v1.14.0

func (d *DefaultAuthenticationProvider) Validate(authPluginName string) bool

type EmptyHandler

type EmptyHandler struct{}

EmptyHandler is a mostly empty implementation for demonstration purposes

func (EmptyHandler) HandleFieldList

func (h EmptyHandler) HandleFieldList(table string, fieldWildcard string) ([]*mysql.Field, error)

HandleFieldList is called for COM_FIELD_LIST packets Note that COM_FIELD_LIST has been deprecated since MySQL 5.7.11 https://dev.mysql.com/doc/dev/mysql-server/latest/page_protocol_com_field_list.html

func (EmptyHandler) HandleOtherCommand

func (h EmptyHandler) HandleOtherCommand(cmd byte, data []byte) error

HandleOtherCommand is called for commands not handled elsewhere

func (EmptyHandler) HandleQuery

func (h EmptyHandler) HandleQuery(query string) (*mysql.Result, error)

HandleQuery is called for COM_QUERY

func (EmptyHandler) HandleStmtClose

func (h EmptyHandler) HandleStmtClose(context any) error

HandleStmtClose is called for COM_STMT_CLOSE

func (EmptyHandler) HandleStmtExecute

func (h EmptyHandler) HandleStmtExecute(context any, query string, args []any) (*mysql.Result, error)

HandleStmtExecute is called for COM_STMT_EXECUTE

func (EmptyHandler) HandleStmtPrepare

func (h EmptyHandler) HandleStmtPrepare(query string) (int, int, any, error)

HandleStmtPrepare is called for COM_STMT_PREPARE

func (EmptyHandler) UseDB

func (h EmptyHandler) UseDB(dbName string) error

UseDB is called for COM_INIT_DB

type EmptyReplicationHandler added in v1.7.0

type EmptyReplicationHandler struct {
	EmptyHandler
}

EmptyReplicationHandler is a empty handler that implements the replication protocol

func (EmptyReplicationHandler) HandleBinlogDump added in v1.7.0

HandleBinlogDump is called for COM_BINLOG_DUMP (non-GTID)

func (EmptyReplicationHandler) HandleBinlogDumpGTID added in v1.7.0

func (h EmptyReplicationHandler) HandleBinlogDumpGTID(gtidSet *mysql.MysqlGTIDSet) (*replication.BinlogStreamer, error)

HandleBinlogDumpGTID is called for COM_BINLOG_DUMP_GTID

func (EmptyReplicationHandler) HandleRegisterSlave added in v1.7.0

func (h EmptyReplicationHandler) HandleRegisterSlave(data []byte) error

HandleRegisterSlave is called for COM_REGISTER_SLAVE

type Handler

type Handler interface {
	// handle COM_INIT_DB command, you can check whether the dbName is valid, or other.
	UseDB(dbName string) error
	// handle COM_QUERY command, like SELECT, INSERT, UPDATE, etc...
	// If Result has a Resultset (SELECT, SHOW, etc...), we will send this as the response, otherwise, we will send Result
	HandleQuery(query string) (*mysql.Result, error)
	// handle COM_FILED_LIST command
	HandleFieldList(table string, fieldWildcard string) ([]*mysql.Field, error)
	// handle COM_STMT_PREPARE, params is the param number for this statement, columns is the column number
	// context will be used later for statement execute
	HandleStmtPrepare(query string) (params int, columns int, context any, err error)
	// handle COM_STMT_EXECUTE, context is the previous one set in prepare
	// query is the statement prepare query, and args is the params for this statement
	HandleStmtExecute(context any, query string, args []any) (*mysql.Result, error)
	// handle COM_STMT_CLOSE, context is the previous one set in prepare
	// this handler has no response
	HandleStmtClose(context any) error
	// handle any other command that is not currently handled by the library,
	// default implementation for this method will return an ER_UNKNOWN_ERROR
	HandleOtherCommand(cmd byte, data []byte) error
}

Handler is what a server needs to implement the client-server protocol

type InMemoryAuthenticationHandler added in v1.14.0

type InMemoryAuthenticationHandler struct {
	// contains filtered or unexported fields
}

InMemoryAuthenticationHandler implements AuthenticationHandler with in-memory credential storage.

func NewInMemoryAuthenticationHandler added in v1.14.0

func NewInMemoryAuthenticationHandler(defaultAuthMethod ...string) *InMemoryAuthenticationHandler

func (*InMemoryAuthenticationHandler) AddUser added in v1.14.0

func (h *InMemoryAuthenticationHandler) AddUser(username, password string, optionalAuthPluginName ...string) error

func (*InMemoryAuthenticationHandler) CheckUsername added in v1.14.0

func (h *InMemoryAuthenticationHandler) CheckUsername(username string) (found bool, err error)

func (*InMemoryAuthenticationHandler) GetCredential added in v1.14.0

func (h *InMemoryAuthenticationHandler) GetCredential(username string) (credential Credential, found bool, err error)

func (*InMemoryAuthenticationHandler) OnAuthFailure added in v1.14.0

func (h *InMemoryAuthenticationHandler) OnAuthFailure(conn *Conn, err error)

func (*InMemoryAuthenticationHandler) OnAuthSuccess added in v1.14.0

func (h *InMemoryAuthenticationHandler) OnAuthSuccess(conn *Conn) error

type ReplicationHandler added in v1.7.0

type ReplicationHandler interface {
	// handle Replication command
	HandleRegisterSlave(data []byte) error
	HandleBinlogDump(pos mysql.Position) (*replication.BinlogStreamer, error)
	HandleBinlogDumpGTID(gtidSet *mysql.MysqlGTIDSet) (*replication.BinlogStreamer, error)
}

ReplicationHandler is for handlers that want to implement the replication protocol

type Server

type Server struct {
	// contains filtered or unexported fields
}

Defines a basic MySQL server with configs.

We do not aim at implementing the whole MySQL connection suite to have the best compatibilities for the clients. The MySQL server can be configured to switch auth methods covering 'mysql_old_password', 'mysql_native_password', 'mysql_clear_password', 'authentication_windows_client', 'sha256_password', 'caching_sha2_password', etc.

However, since some old auth methods are considered broken with security issues. MySQL major versions like 5.7 and 8.0 default to 'mysql_native_password' or 'caching_sha2_password', and most MySQL clients should have already supported at least one of the three auth methods 'mysql_native_password', 'caching_sha2_password', and 'sha256_password'. Thus here we will only support these three auth methods, and use 'mysql_native_password' as default for maximum compatibility with the clients and leave the other two as config options.

The MySQL doc states that 'mysql_old_password' will be used if 'CLIENT_PROTOCOL_41' or 'CLIENT_SECURE_CONNECTION' flag is not set. We choose to drop the support for insecure 'mysql_old_password' auth method and require client capability 'CLIENT_PROTOCOL_41' and 'CLIENT_SECURE_CONNECTION' are set. Besides, if 'CLIENT_PLUGIN_AUTH' is not set, we fallback to 'mysql_native_password' auth method.

func NewDefaultServer

func NewDefaultServer() *Server

NewDefaultServer: New mysql server with default settings.

NOTES: TLS support will be enabled by default with auto-generated CA and server certificates (however, you can still use non-TLS connection). By default, it will verify the client certificate if present. You can enable TLS support on the client side without providing a client-side certificate. So only when you need the server to verify client identity for maximum security, you need to set a signed certificate for the client.

func NewServer

func NewServer(serverVersion string, collationId uint8, defaultAuthMethod string, rsaKey *rsa.PrivateKey, tlsConfig *tls.Config) *Server

NewServer: New mysql server with customized settings.

NOTES: You can control the authentication methods and TLS settings here.

For auth method, you can specify one of the supported methods 'mysql_native_password', 'caching_sha2_password', and 'sha256_password'. The specified auth method will be enforced by the server in the connection phase. That means, client will be asked to switch auth method if the supplied auth method is different from the server default.

For TLS support, you can specify self-signed or CA-signed certificates and decide whether the client needs to provide a signed or unsigned certificate to provide different level of security.

The rsaKey parameter is used for password encryption on non-TLS connections with 'caching_sha2_password' and 'sha256_password'. If it's is nil, it will attempt to extract an RSA key from tlsConfig.Certificates[0]. If no RSA key is available, non-TLS connections will not be supported for these auth methods (TLS connections will still work).

func NewServerWithAuth added in v1.14.0

func NewServerWithAuth(serverVersion string, collationId uint8, defaultAuthMethod string, rsaKey *rsa.PrivateKey, tlsConfig *tls.Config, authProvider AuthenticationProvider) *Server

func (*Server) InvalidateCache

func (s *Server) InvalidateCache(username string, host string)

func (*Server) NewConn added in v1.12.0

func (s *Server) NewConn(conn net.Conn, user string, password string, h Handler) (*Conn, error)

NewConn: create connection with default server settings

func (*Server) NewCustomizedConn added in v1.12.0

func (s *Server) NewCustomizedConn(conn net.Conn, authHandler AuthenticationHandler, h Handler) (*Conn, error)

type Stmt

type Stmt struct {
	Query string
	Args  []any

	Context any

	// PreparedStmt contains common fields shared with client.Stmt for proxy passthrough
	stmt.PreparedStmt
}

func (*Stmt) ResetParams

func (s *Stmt) ResetParams()

func (*Stmt) Rest

func (s *Stmt) Rest(params int, columns int, context any)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL