Documentation
¶
Index ¶
- Constants
- Variables
- func AuthenticateBackend(conn net.Conn, user, password, authDB string) error
- func BuildOpMsg(flags uint32, doc bson.Raw) []byte
- func BuildOpReply(doc bson.Raw) []byte
- func CommandDB(doc bson.Raw) string
- func CommandName(doc bson.Raw) (string, error)
- func ExtractSASLPayload(doc bson.Raw) (payload []byte, conversationID int32, done bool, err error)
- func NextRequestID() int32
- func ParseOpMsgBody(body []byte) (flags uint32, doc bson.Raw, err error)
- func ParseOpQueryBody(body []byte) (doc bson.Raw, err error)
- func RewriteTopology(body []byte, proxyAddr string) []byte
- func RewriteTopologyWithMap(body []byte, proxyAddr string, topologyMap map[string]string) []byte
- func SendErrorAsHelloReply(conn net.Conn, hello *ClientHello, code int32, message string)
- func WriteMessage(conn net.Conn, msg *Message) error
- type ClientHandshakeResult
- func CompleteHandshake(clientConn net.Conn, hello *ClientHello, backendHelloDoc bson.Raw, ...) (*ClientHandshakeResult, error)
- func CompleteHandshakeWithTopologyMap(clientConn net.Conn, hello *ClientHello, backendHelloDoc bson.Raw, ...) (*ClientHandshakeResult, error)
- func HandleClientHandshake(clientConn net.Conn) (*ClientHandshakeResult, error)
- type ClientHello
- type Header
- type Message
- func BuildErrorReply(requestID int32, code int32, message string) (*Message, error)
- func BuildHelloCommand(db string) (*Message, error)
- func BuildSASLContinueCommand(payload []byte, conversationID int32, db string) (*Message, error)
- func BuildSASLContinueReply(requestID int32, payload []byte, conversationID int32) (*Message, error)
- func BuildSASLStartCommand(mechanism string, payload []byte, db string) (*Message, error)
- func BuildSASLStartReply(requestID int32, payload []byte, conversationID int32) (*Message, error)
- func ForwardMessage(dst, src net.Conn) (*Message, error)
- func NewOpMsgMessage(responseTo int32, doc bson.Raw) *Message
- func NewOpReplyMessage(responseTo int32, doc bson.Raw) *Message
- func ReadMessage(conn net.Conn) (*Message, error)
- type SCRAMClient
- type SCRAMServer
- type TopologyRewriter
- func (r *TopologyRewriter) Close() error
- func (r *TopologyRewriter) LocalAddr() net.Addr
- func (r *TopologyRewriter) Read(p []byte) (int, error)
- func (r *TopologyRewriter) RemoteAddr() net.Addr
- func (r *TopologyRewriter) SetDeadline(t time.Time) error
- func (r *TopologyRewriter) SetReadDeadline(t time.Time) error
- func (r *TopologyRewriter) SetWriteDeadline(t time.Time) error
- func (r *TopologyRewriter) Write(p []byte) (int, error)
Constants ¶
const ( OpQuery int32 = 2004 // legacy OP_QUERY (used for initial isMaster handshake) OpReply int32 = 1 // legacy OP_REPLY OpMsg int32 = 2013 )
MongoDB wire protocol opcodes.
const ( FlagChecksumPresent uint32 = 1 << 0 FlagMoreToCome uint32 = 1 << 1 FlagExhaustAllowed uint32 = 1 << 16 )
OP_MSG flag bits.
const ( SectionBody byte = 0 SectionDocumentSequence byte = 1 )
OP_MSG section kinds.
const DummyPassword = "waypoint"
DummyPassword is the well-known password that MongoDB clients may use when connecting through waypoint with credentials. Tailscale identity is the real credential; this password exists only to satisfy the SCRAM protocol. Clients can also connect with NO credentials (preferred).
const HeaderSize = headerSize
HeaderSize is the size of a MongoDB wire protocol message header (16 bytes).
Variables ¶
var ErrAuthFailed = errors.New("authentication failed")
ErrAuthFailed marks a handshake that failed because the client presented wrong credentials (e.g. a SCRAM client-proof mismatch). The proxy uses this to treat the failure as a client auth error — logged at warning level and counted as an auth failure — rather than a proxy/backend fault.
Functions ¶
func AuthenticateBackend ¶
AuthenticateBackend performs the full SCRAM-SHA-256 exchange with the backend after the hello handshake. authDB is typically "admin".
func BuildOpMsg ¶
BuildOpMsg constructs an OP_MSG wire body from a BSON document.
func BuildOpReply ¶
BuildOpReply constructs a legacy OP_REPLY message body from a BSON document.
func CommandName ¶
CommandName extracts the command name (first key) from a BSON document.
func ExtractSASLPayload ¶
ExtractSASLPayload extracts the binary payload and conversationId from a saslStart/saslContinue response document.
func NextRequestID ¶
func NextRequestID() int32
NextRequestID returns a monotonically increasing request ID.
func ParseOpMsgBody ¶
ParseOpMsgBody extracts the flags and body BSON document from an OP_MSG body. Only parses the first kind-0 section (single document body). Handles FlagChecksumPresent by excluding the trailing 4-byte CRC32 from section parsing.
func ParseOpQueryBody ¶
ParseOpQueryBody extracts the query document from a legacy OP_QUERY body. OP_QUERY body layout: flags(4) + fullCollectionName(cstring) + numberToSkip(4) + numberToReturn(4) + query(BSON)
func RewriteTopology ¶
RewriteTopology inspects an OP_MSG response body and, if it looks like a hello/isMaster response with replica set topology info, replaces all member addresses with proxyAddr. Returns the (possibly modified) body.
The detection is lightweight: if the document contains a "hosts" field, it's treated as a topology response. Non-topology responses pass through unchanged with minimal overhead (one BSON key lookup).
Handles FlagChecksumPresent: if the checksum flag is set, the trailing 4-byte CRC32 is stripped and the flag is cleared, since the checksum would be invalidated by rewriting.
func RewriteTopologyWithMap ¶
RewriteTopologyWithMap is like RewriteTopology, but it maps each backend member address to a specific proxy address when topologyMap contains one. Addresses missing from topologyMap fall back to proxyAddr.
func SendErrorAsHelloReply ¶
func SendErrorAsHelloReply(conn net.Conn, hello *ClientHello, code int32, message string)
SendErrorAsHelloReply sends an error in the appropriate format based on whether the client sent a legacy OP_QUERY or modern OP_MSG hello. Use this for errors that occur after reading the client hello but before completing the handshake.
Types ¶
type ClientHandshakeResult ¶
type ClientHandshakeResult struct {
AuthDB string // the authentication database (usually "admin")
Username string // the username from the SCRAM exchange (empty if no auth)
// FirstCommand is non-nil when the client connected without credentials.
// The proxy must forward this message to the backend before starting relay.
FirstCommand *Message
}
ClientHandshakeResult contains information extracted from the client's handshake.
func CompleteHandshake ¶
func CompleteHandshake(clientConn net.Conn, hello *ClientHello, backendHelloDoc bson.Raw, proxyAddr string) (*ClientHandshakeResult, error)
CompleteHandshake sends the hello reply and handles optional SCRAM-SHA-256. backendHelloDoc is the backend's real hello response used for capabilities and topology. proxyAddr is used to rewrite topology fields (hosts, me, etc.).
Supports two client paths:
- No credentials (preferred): sends hello reply, reads next message. If it's a regular command, buffers it in FirstCommand.
- With credentials: full SCRAM-SHA-256 exchange using DummyPassword.
func CompleteHandshakeWithTopologyMap ¶
func CompleteHandshakeWithTopologyMap(clientConn net.Conn, hello *ClientHello, backendHelloDoc bson.Raw, proxyAddr string, topologyMap map[string]string) (*ClientHandshakeResult, error)
CompleteHandshakeWithTopologyMap is like CompleteHandshake, but rewrites each known backend replica-set member to its configured proxy address.
func HandleClientHandshake ¶
func HandleClientHandshake(clientConn net.Conn) (*ClientHandshakeResult, error)
HandleClientHandshake is a convenience wrapper that uses a fabricated hello response. Prefer ReadClientHello + CompleteHandshake with the backend's real hello for production use.
type ClientHello ¶
type ClientHello struct {
Message *Message // the raw hello message
Doc bson.Raw // parsed hello document
IsLegacy bool // true if sent as OP_QUERY (legacy isMaster)
AuthDB string // authentication database (usually "admin")
Username string // from saslSupportedMechs or SCRAM, empty if no auth
SpecAuth bson.Raw // speculativeAuthenticate document, nil if not present
}
ClientHello contains the parsed client hello message, before the proxy replies.
func ReadClientHello ¶
func ReadClientHello(clientConn net.Conn) (*ClientHello, error)
ReadClientHello reads and parses the client's initial hello/isMaster message without sending a reply. The caller should use CompleteHandshake to send the reply after obtaining the backend's real hello response.
type Message ¶
Message is a complete MongoDB wire protocol message (header + body).
func BuildErrorReply ¶
BuildErrorReply builds a MongoDB error response.
func BuildHelloCommand ¶
BuildHelloCommand builds a hello command for authenticating to the backend.
func BuildSASLContinueCommand ¶
BuildSASLContinueCommand builds a saslContinue command for authenticating to the backend.
func BuildSASLContinueReply ¶
func BuildSASLContinueReply(requestID int32, payload []byte, conversationID int32) (*Message, error)
BuildSASLContinueReply builds the server's final response to a saslContinue command. payload is the SCRAM server-final-message bytes.
func BuildSASLStartCommand ¶
BuildSASLStartCommand builds a saslStart command for authenticating to the backend.
func BuildSASLStartReply ¶
BuildSASLStartReply builds the server's response to a saslStart command. payload is the SCRAM server-first-message bytes, conversationID identifies the exchange.
func ForwardMessage ¶
ForwardMessage reads a raw message from src and writes it to dst unchanged. Returns the raw bytes for inspection if needed.
func NewOpMsgMessage ¶
NewOpMsgMessage creates a complete Message from a BSON document.
func NewOpReplyMessage ¶
NewOpReplyMessage creates a complete OP_REPLY Message from a BSON document.
type SCRAMClient ¶
type SCRAMClient struct {
// contains filtered or unexported fields
}
SCRAMClient performs SCRAM-SHA-256 authentication with a MongoDB backend.
func NewSCRAMClient ¶
func NewSCRAMClient(user, password string) *SCRAMClient
NewSCRAMClient creates a SCRAM-SHA-256 client for backend authentication.
func (*SCRAMClient) ClientFinalMessage ¶
func (s *SCRAMClient) ClientFinalMessage(serverFirst string) (string, error)
ClientFinalMessage processes the server-first-message and generates the client-final-message.
func (*SCRAMClient) ClientFirstMessage ¶
func (s *SCRAMClient) ClientFirstMessage() string
ClientFirstMessage generates the SCRAM client-first-message.
func (*SCRAMClient) VerifyServerFinal ¶
func (s *SCRAMClient) VerifyServerFinal(serverFinal string) error
VerifyServerFinal verifies the server-final-message signature.
type SCRAMServer ¶
type SCRAMServer struct {
// contains filtered or unexported fields
}
SCRAMServer holds state for faking SCRAM-SHA-256 to a client. The proxy accepts clients that authenticate with the well-known dummy password (DummyPassword) since Tailscale identity is the real credential.
func NewSCRAMServer ¶
func NewSCRAMServer() *SCRAMServer
NewSCRAMServer creates a fake SCRAM-SHA-256 server with random parameters.
type TopologyRewriter ¶
type TopologyRewriter struct {
// contains filtered or unexported fields
}
TopologyRewriter wraps a net.Conn (the backend connection) and rewrites MongoDB topology responses so replica set member addresses point to the proxy instead of the backend's internal addresses.
It implements net.Conn. Reads from this connection return bytes with topology fields rewritten. Writes pass through unchanged.
This is inserted between restrict.Relay and the real backend connection so that the raw relay's byte counting still works correctly.
func NewTopologyRewriter ¶
func NewTopologyRewriter(conn net.Conn, proxyAddr string) *TopologyRewriter
NewTopologyRewriter creates a wrapper that rewrites topology responses read from conn, replacing member addresses with proxyAddr.
func NewTopologyRewriterWithMap ¶
func NewTopologyRewriterWithMap(conn net.Conn, proxyAddr string, topologyMap map[string]string) *TopologyRewriter
NewTopologyRewriterWithMap creates a wrapper that rewrites topology responses using topologyMap for known replica set members and proxyAddr as the fallback for unknown members.
func (*TopologyRewriter) Close ¶
func (r *TopologyRewriter) Close() error
Close closes the underlying connection.
func (*TopologyRewriter) LocalAddr ¶
func (r *TopologyRewriter) LocalAddr() net.Addr
LocalAddr returns the underlying connection's local address.
func (*TopologyRewriter) Read ¶
func (r *TopologyRewriter) Read(p []byte) (int, error)
Read reads from the underlying connection. If a complete OP_MSG is available and contains topology info, it's rewritten before returning.
For simplicity and reliability, this uses a message-boundary-aware approach: read a complete wire message, optionally rewrite it, then serve it to the caller.
func (*TopologyRewriter) RemoteAddr ¶
func (r *TopologyRewriter) RemoteAddr() net.Addr
RemoteAddr returns the underlying connection's remote address.
func (*TopologyRewriter) SetDeadline ¶
func (r *TopologyRewriter) SetDeadline(t time.Time) error
SetDeadline sets the underlying connection's deadline.
func (*TopologyRewriter) SetReadDeadline ¶
func (r *TopologyRewriter) SetReadDeadline(t time.Time) error
SetReadDeadline sets the underlying connection's read deadline.
func (*TopologyRewriter) SetWriteDeadline ¶
func (r *TopologyRewriter) SetWriteDeadline(t time.Time) error
SetWriteDeadline sets the underlying connection's write deadline.