Documentation ¶
Overview ¶
Package postgresql contains PgDecryptor reads data from PostgreSQL databases, finds AcraStructs and decrypt them.
Index ¶
- Constants
- Variables
- func FetchQueryFromParse(data []byte) ([]byte, error)
- func GetParameterFormatByIndex(i int, params []uint16) (base.BoundValueFormat, error)
- func NewPgBoundValue(data []byte, format base.BoundValueFormat) base.BoundValue
- func NewPgError(message string) ([]byte, error)
- func NewProxyFactory(proxySetting base.ProxySetting, store keystore.DecryptionKeyStore, ...) (base.ProxyFactory, error)
- type BindPacket
- func (p *BindPacket) GetParameters() ([]base.BoundValue, error)
- func (p *BindPacket) GetResultFormats() ([]uint16, error)
- func (p *BindPacket) MarshalInto(buffer *bytes.Buffer) (int, error)
- func (p *BindPacket) PortalName() string
- func (p *BindPacket) SetParameters(values []base.BoundValue)
- func (p *BindPacket) StatementName() string
- func (p *BindPacket) Zeroize()
- type ColumnData
- type Cursor
- type DataTypeFormat
- func (p *DataTypeFormat) GetColumnName() string
- func (p *DataTypeFormat) GetDBDataTypeID() uint32
- func (p *DataTypeFormat) GetDefaultDataValue() *string
- func (p *DataTypeFormat) GetResponseOnFail() common.ResponseOnFail
- func (p *DataTypeFormat) IsBinaryDataOperation() bool
- func (p *DataTypeFormat) IsBinaryFormat() bool
- type EncryptionSettingExtractor
- type ExecutePacket
- type PacketHandler
- func (packet *PacketHandler) GetBindData() (*BindPacket, error)
- func (packet *PacketHandler) GetExecuteData() (*ExecutePacket, error)
- func (packet *PacketHandler) GetParameterDescriptionData() (*pgproto3.ParameterDescription, error)
- func (packet *PacketHandler) GetParseData() (*ParsePacket, error)
- func (packet *PacketHandler) GetRowDescriptionData() (*pgproto3.RowDescription, error)
- func (packet *PacketHandler) GetSimpleQuery() (string, error)
- func (packet *PacketHandler) IsAlreadyStarted() bool
- func (packet *PacketHandler) IsBind() bool
- func (packet *PacketHandler) IsBindComplete() bool
- func (packet *PacketHandler) IsCommandComplete() bool
- func (packet *PacketHandler) IsDataRow() bool
- func (packet *PacketHandler) IsEmptyQueryResponse() bool
- func (packet *PacketHandler) IsErrorResponse() bool
- func (packet *PacketHandler) IsExecute() bool
- func (packet *PacketHandler) IsNoData() bool
- func (packet *PacketHandler) IsParameterDescription() bool
- func (packet *PacketHandler) IsParse() bool
- func (packet *PacketHandler) IsParseComplete() bool
- func (packet *PacketHandler) IsPortalSuspended() bool
- func (packet *PacketHandler) IsReadyForQuery() bool
- func (packet *PacketHandler) IsRowDescription() bool
- func (packet *PacketHandler) IsSSLRequestAllowed() bool
- func (packet *PacketHandler) IsSSLRequestDeny() bool
- func (packet *PacketHandler) IsSimpleQuery() bool
- func (packet *PacketHandler) Marshal() ([]byte, error)
- func (packet *PacketHandler) ReadClientPacket() error
- func (packet *PacketHandler) ReadPacket() error
- func (packet *PacketHandler) ReplaceBind(bindPacket *BindPacket) error
- func (packet *PacketHandler) ReplaceQuery(newQuery string)
- func (packet *PacketHandler) Reset()
- func (packet *PacketHandler) SetParsePacket(parsePacket *ParsePacket) error
- func (packet *PacketHandler) SetStarted()
- type PacketType
- type ParsePacket
- type PgPortal
- type PgPreparedStatement
- type PgPreparedStatementRegistry
- func (r *PgPreparedStatementRegistry) AddCursor(cursor Cursor) error
- func (r *PgPreparedStatementRegistry) AddStatement(statement PreparedStatement) error
- func (r *PgPreparedStatementRegistry) CursorByName(name string) (Cursor, error)
- func (r *PgPreparedStatementRegistry) DeleteCursor(name string) error
- func (r *PgPreparedStatementRegistry) DeleteStatement(name string) error
- func (r *PgPreparedStatementRegistry) StatementByName(name string) (PreparedStatement, error)
- type PgProtocolState
- type PgProxy
- func (proxy *PgProxy) AddClientIDObserver(observer base.ClientIDObserver)
- func (proxy *PgProxy) AddQueryObserver(obs postgresql.QueryObserver)
- func (proxy *PgProxy) ProxyClientConnection(ctx context.Context, errCh chan<- base.ProxyError)
- func (proxy *PgProxy) ProxyDatabaseConnection(ctx context.Context, errCh chan<- base.ProxyError)
- func (proxy *PgProxy) RegisteredObserversCount() int
- func (proxy *PgProxy) SubscribeOnAllColumnsDecryption(subscriber base.DecryptionSubscriber)
- func (proxy *PgProxy) Unsubscribe(subscriber base.DecryptionSubscriber)
- type PgSQLDataDecoderProcessor
- type PgSQLDataEncoderProcessor
- type PreparedStatement
- type PreparedStatementsQuery
- func (encryptor *PreparedStatementsQuery) ID() string
- func (encryptor *PreparedStatementsQuery) OnBind(ctx context.Context, statement *pg_query.ParseResult, values []base.BoundValue) ([]base.BoundValue, bool, error)
- func (encryptor *PreparedStatementsQuery) OnQuery(ctx context.Context, query postgresql.OnQueryObject) (postgresql.OnQueryObject, bool, error)
Constants ¶
const ( // DataRowLengthBufSize each postgresql packet contain 4 byte that store length of message contents in bytes, including self DataRowLengthBufSize = 4 // random chosen OutputDefaultSize = 1024 // https://www.postgresql.org/docs/9.4/static/protocol-message-formats.html DataRowMessageType byte = 'D' QueryMessageType byte = 'Q' ParseMessageType byte = 'P' BindMessageType byte = 'B' ExecuteMessageType byte = 'E' ErrorResponseType byte = 'E' ParseCompleteMessageType byte = '1' BindCompleteMessageType byte = '2' ReadyForQueryMessageType byte = 'Z' RowDescriptionType byte = 'T' ParameterDescriptionType byte = 't' CommandCompleteType byte = 'C' EmptyQueryResponseType = 'I' NoDataType = 'n' PortalSuspendedType = 's' ClientStopTimeout = time.Second * 2 )
PgSQL constant sizes and types.
const ( // NullColumnValue indicates that column has null value without any data // https://www.postgresql.org/docs/9.3/static/protocol-message-formats.html NullColumnValue int32 = -1 )
const WithoutMessageType = 0
WithoutMessageType used to indicate that MessageType wasn't set and shouldn't marshaled
Variables ¶
var ( SSLRequest = []byte{4, 210, 22, 47} CancelRequest = []byte{4, 210, 22, 46} StartupRequest = []byte{0, 3, 0, 0} GSSENCRequest = []byte{4, 210, 22, 48} // Length is always 8 plus SSLRequest SSLRequestHeader = bytes.Join([][]byte{{0x00, 0x00, 0x00, 0x08}, SSLRequest}, []byte{}) // Length is always 16 plus CancelRequest CancelRequestHeader = bytes.Join([][]byte{{0x00, 0x00, 0x00, 0x10}, CancelRequest}, []byte{}) // Length is always 8 plus GSSENCRequest GSSENCRequestHeader = bytes.Join([][]byte{{0x00, 0x00, 0x00, 0x08}, GSSENCRequest}, []byte{}) )
Constant values of specific postgresql messages - https://www.postgresql.org/docs/current/static/protocol-message-formats.html
var ( ErrInvalidPreparedStatementRegistry = errors.New("ClientSession contains invalid PreparedStatementRegistry") ErrInvalidCursorRegistry = errors.New("ClientSession contains invalid CursorRegistry") ErrInvalidProtocolState = errors.New("ClientSession contains invalid ProtocolState") )
Errors returned when initializing session registries.
var ( ErrStatementNotFound = errors.New("no prepared statement with given name") ErrCursorNotFound = errors.New("no cursor with given name") )
Errors returned by prepared statement registry.
var ( ErrStatementAlreadyInRegistry = errors.New("prepared statement already store in registry") ErrStatementNotPresentInRegistry = errors.New("prepared statement not present in registry") )
ErrStatementAlreadyInRegistry represent an error that prepared statement already exist in session registry
var ErrArrayTooBig = errors.New("array too big")
ErrArrayTooBig signals that an array it too big to fit into a packet.
var ErrNilPendingPacket = errors.New("nil pending packet")
ErrNilPendingPacket error when took nil instead of pending packet
var ErrNotEnoughFormats = errors.New("format index out of range")
ErrNotEnoughFormats is returned when Bind packet is malformed and does not contain enough formats for values.
var ErrPacketTruncated = errors.New("invalid packet, too short")
ErrPacketTruncated signals that the packet is too short and cannot be parsed
var ErrRemoveFromEmptyPendingList = errors.New("removing from empty pending list")
ErrRemoveFromEmptyPendingList error after trying to remove object from empty list
var ErrTerminatorNotFound = errors.New("invalid string, terminator not found")
ErrTerminatorNotFound not found terminator for string value
var ErrUnknownFormat = errors.New("unknown Bind packet format")
ErrUnknownFormat is returned when Bind packet contains a value format that we don't recognize.
var ErrUnsupportedPacketType = errors.New("unsupported postgresql message type")
ErrUnsupportedPacketType error when recognized unsupported message type or new added to postgresql wire protocol
var ErrUnsupportedPendingPacketType = errors.New("unsupported pending packet type")
ErrUnsupportedPendingPacketType error after using unknown type of structure
var ReadyForQuery = []byte{'Z', 0, 0, 0, 5, 'I'}
ReadyForQuery - 'Z' ReadyForQuery, 0 0 0 5 length, 'I' idle status https://www.postgresql.org/docs/9.3/static/protocol-message-formats.html
var TerminatePacket = []byte{'X', 0, 0, 0, 4}
TerminatePacket sent by client to close connection with db https://www.postgresql.org/docs/9.4/static/protocol-message-formats.html
Functions ¶
func FetchQueryFromParse ¶
FetchQueryFromParse return Query value from Parse packet payload (without message type and length of packet)
Find first null terminator as end of prepared statement name and find next which terminate query string Parse packet has next structure: 'P' + int32 (length of packet) + NullTerminatedString (prepared statement name) + + NullTerminatedString (query) + int16 (number of next int32 parameters) + int32[n] (parameters) https://www.postgresql.org/docs/9.3/protocol-message-formats.html
func GetParameterFormatByIndex ¶
func GetParameterFormatByIndex(i int, params []uint16) (base.BoundValueFormat, error)
GetParameterFormatByIndex return parameter format according to PostgreSQL rules. If only one parameter passed then it propagated for every next parameter. If no params then by default it is TextFormat
func NewPgBoundValue ¶
func NewPgBoundValue(data []byte, format base.BoundValueFormat) base.BoundValue
NewPgBoundValue makes a pgsql BoundValue from copied input data.
func NewProxyFactory ¶
func NewProxyFactory(proxySetting base.ProxySetting, store keystore.DecryptionKeyStore, tokenizer common.Pseudoanonymizer) (base.ProxyFactory, error)
NewProxyFactory return new proxyFactory
Types ¶
type BindPacket ¶
type BindPacket struct {
// contains filtered or unexported fields
}
BindPacket represents "Bind" packet of the PostgreSQL protocol, containing bound parameters of a prepared statement. See https://www.postgresql.org/docs/current/protocol-message-formats.html
func NewBindPacket ¶
func NewBindPacket(data []byte) (*BindPacket, error)
NewBindPacket parses Bind packet from data.
func (*BindPacket) GetParameters ¶
func (p *BindPacket) GetParameters() ([]base.BoundValue, error)
GetParameters extracts statement parameters from Bind packet.
func (*BindPacket) GetResultFormats ¶
func (p *BindPacket) GetResultFormats() ([]uint16, error)
GetResultFormats return formats expected in result data rows on Bind + Execute
func (*BindPacket) MarshalInto ¶
func (p *BindPacket) MarshalInto(buffer *bytes.Buffer) (int, error)
MarshalInto packet contents into packet protocol data buffer.
func (*BindPacket) PortalName ¶
func (p *BindPacket) PortalName() string
PortalName returns the name of the portal created by this request. An empty name means unnamed portal.
func (*BindPacket) SetParameters ¶
func (p *BindPacket) SetParameters(values []base.BoundValue)
SetParameters updates statement parameters from Bind packet.
func (*BindPacket) StatementName ¶
func (p *BindPacket) StatementName() string
StatementName returns the name of the statement bound by this request. An empty name means unnamed statement.
type ColumnData ¶
type ColumnData struct { LengthBuf [4]byte // contains filtered or unexported fields }
ColumnData hold column length and data
func (*ColumnData) GetData ¶
func (column *ColumnData) GetData() []byte
GetData return raw data, decoded from db format to binary
func (*ColumnData) IsNull ¶
func (column *ColumnData) IsNull() bool
IsNull return true if column has null value
func (*ColumnData) Length ¶
func (column *ColumnData) Length() int
Length return column length converted from LengthBuf
func (*ColumnData) ReadLength ¶
func (column *ColumnData) ReadLength(reader io.Reader) error
ReadLength of column
func (*ColumnData) SetData ¶
func (column *ColumnData) SetData(newData []byte)
SetData to column and update LengthBuf with new size
func (*ColumnData) SetDataLength ¶
func (column *ColumnData) SetDataLength(length uint32)
SetDataLength set into LengthBuf
type Cursor ¶
type Cursor interface { Name() string PreparedStatement() PreparedStatement }
Cursor is used to iterate over a prepared statement. It can be either a textual SQL statement from "DEFINE CURSOR", or a database protocol equivalent.
type DataTypeFormat ¶
type DataTypeFormat struct {
// contains filtered or unexported fields
}
DataTypeFormat implementation of type_awareness.DataTypeFormat for PostgreSQL
func NewDataTypeFormat ¶
func NewDataTypeFormat(columnInfo base.ColumnInfo, columnSetting config.ColumnEncryptionSetting) *DataTypeFormat
NewDataTypeFormat create new DataTypeFormat from ColumnInfo and ColumnEncryptionSetting
func (*DataTypeFormat) GetColumnName ¶
func (p *DataTypeFormat) GetColumnName() string
GetColumnName return ColumnName
func (*DataTypeFormat) GetDBDataTypeID ¶
func (p *DataTypeFormat) GetDBDataTypeID() uint32
GetDBDataTypeID return DBDataTypeID
func (*DataTypeFormat) GetDefaultDataValue ¶
func (p *DataTypeFormat) GetDefaultDataValue() *string
GetDefaultDataValue return DefaultDataValue
func (*DataTypeFormat) GetResponseOnFail ¶
func (p *DataTypeFormat) GetResponseOnFail() common.ResponseOnFail
GetResponseOnFail return ResponseOnFail
func (*DataTypeFormat) IsBinaryDataOperation ¶
func (p *DataTypeFormat) IsBinaryDataOperation() bool
IsBinaryDataOperation check from columnSetting if binaryOperation
func (*DataTypeFormat) IsBinaryFormat ¶
func (p *DataTypeFormat) IsBinaryFormat() bool
IsBinaryFormat check if columnInfo is binary
type EncryptionSettingExtractor ¶
type EncryptionSettingExtractor struct {
// contains filtered or unexported fields
}
EncryptionSettingExtractor uses QueryDataEncryptor to extract ColumnEncryptionSetting for every column in the result
func NewEncryptionSettingExtractor ¶
func NewEncryptionSettingExtractor(ctx context.Context, schema config.TableSchemaStore) (EncryptionSettingExtractor, error)
NewEncryptionSettingExtractor returns new initialized EncryptionSettingExtractor
func (EncryptionSettingExtractor) GetEncryptorSettingsForQuery ¶
func (extractor EncryptionSettingExtractor) GetEncryptorSettingsForQuery(object postgresql.OnQueryObject) ([]*encryptor.QueryDataItem, error)
GetEncryptorSettingsForQuery walk through the query and match result columns in SELECT and INSERT/DELETE + RETURNING statements to the ColumnEncryptionSetting
type ExecutePacket ¶
type ExecutePacket struct {
// contains filtered or unexported fields
}
ExecutePacket represents "Execute" packet of the PostgreSQL protocol, containing the name of the portal to query for data. See https://www.postgresql.org/docs/current/protocol-message-formats.html
func NewExecutePacket ¶
func NewExecutePacket(data []byte) (*ExecutePacket, error)
NewExecutePacket parses Execute packet from data.
func (*ExecutePacket) PortalName ¶
func (p *ExecutePacket) PortalName() string
PortalName returns the name of the portal queried by this request. An empty name means unnamed portal.
func (*ExecutePacket) Zeroize ¶
func (p *ExecutePacket) Zeroize()
Zeroize sensitive data in the packet.
type PacketHandler ¶
type PacketHandler struct { Columns []*ColumnData // contains filtered or unexported fields }
PacketHandler hold state of postgresql packet and process data rows every postgresql packet (except first packet Startup/SSLRequest) has struct as like MessageType[1] + PacketLength[4] + PacketData[N] where numbers are size in bytes and N depends from value in PacketLength
func NewClientSidePacketHandler ¶
func NewClientSidePacketHandler(reader io.Reader, writer *bufio.Writer, logger *logrus.Entry) (*PacketHandler, error)
NewClientSidePacketHandler return new PacketHandler with initialized own logger for client's packets
func NewDbSidePacketHandler ¶
func NewDbSidePacketHandler(reader io.Reader, writer *bufio.Writer, logger *logrus.Entry) (*PacketHandler, error)
NewDbSidePacketHandler return new PacketHandler with initialized own logger for databases's packets
func (*PacketHandler) GetBindData ¶
func (packet *PacketHandler) GetBindData() (*BindPacket, error)
GetBindData returns parsed Bind packet data. Use this only if IsBind() is true.
func (*PacketHandler) GetExecuteData ¶
func (packet *PacketHandler) GetExecuteData() (*ExecutePacket, error)
GetExecuteData returns parsed Execute packet data. Use this only if IsExecute() is true.
func (*PacketHandler) GetParameterDescriptionData ¶
func (packet *PacketHandler) GetParameterDescriptionData() (*pgproto3.ParameterDescription, error)
GetParameterDescriptionData return parsed ParameterDescription packet
func (*PacketHandler) GetParseData ¶
func (packet *PacketHandler) GetParseData() (*ParsePacket, error)
GetParseData returns parsed Parse packet data. Use this only if IsParse() is true.
func (*PacketHandler) GetRowDescriptionData ¶
func (packet *PacketHandler) GetRowDescriptionData() (*pgproto3.RowDescription, error)
GetRowDescriptionData return parsed RowDescription packet
func (*PacketHandler) GetSimpleQuery ¶
func (packet *PacketHandler) GetSimpleQuery() (string, error)
GetSimpleQuery return query value as string from Query packet
func (*PacketHandler) IsAlreadyStarted ¶
func (packet *PacketHandler) IsAlreadyStarted() bool
IsAlreadyStarted returns true if startup packet is already received and packet handler excepts general messages.
func (*PacketHandler) IsBind ¶
func (packet *PacketHandler) IsBind() bool
IsBind return true if packet has Bind type
func (*PacketHandler) IsBindComplete ¶
func (packet *PacketHandler) IsBindComplete() bool
IsBindComplete return true if packet has BindComplete type
func (*PacketHandler) IsCommandComplete ¶
func (packet *PacketHandler) IsCommandComplete() bool
IsCommandComplete return true if packet has CommandComplete type
func (*PacketHandler) IsDataRow ¶
func (packet *PacketHandler) IsDataRow() bool
IsDataRow return true if packet has DataRow type
func (*PacketHandler) IsEmptyQueryResponse ¶
func (packet *PacketHandler) IsEmptyQueryResponse() bool
IsEmptyQueryResponse returns True if packet is EmptyQueryResponse packet type
func (*PacketHandler) IsErrorResponse ¶
func (packet *PacketHandler) IsErrorResponse() bool
IsErrorResponse returns True if it is ErrorResponse from the database
func (*PacketHandler) IsExecute ¶
func (packet *PacketHandler) IsExecute() bool
IsExecute return true if packet has Execute type from the db driver
func (*PacketHandler) IsNoData ¶
func (packet *PacketHandler) IsNoData() bool
IsNoData returns True if it is NoData response packet type
func (*PacketHandler) IsParameterDescription ¶
func (packet *PacketHandler) IsParameterDescription() bool
IsParameterDescription return true if packet has ParameterDescription type
func (*PacketHandler) IsParse ¶
func (packet *PacketHandler) IsParse() bool
IsParse return true if packet has Parse type
func (*PacketHandler) IsParseComplete ¶
func (packet *PacketHandler) IsParseComplete() bool
IsParseComplete return true if packet has ParseComplete type
func (*PacketHandler) IsPortalSuspended ¶
func (packet *PacketHandler) IsPortalSuspended() bool
IsPortalSuspended returns True if it is PortalSuspended packet type
func (*PacketHandler) IsReadyForQuery ¶
func (packet *PacketHandler) IsReadyForQuery() bool
IsReadyForQuery returns true if packet has ReadyForQuery type.
func (*PacketHandler) IsRowDescription ¶
func (packet *PacketHandler) IsRowDescription() bool
IsRowDescription return true if packet has RowDescription type
func (*PacketHandler) IsSSLRequestAllowed ¶
func (packet *PacketHandler) IsSSLRequestAllowed() bool
IsSSLRequestAllowed returns true server allowed switch to SSL
func (*PacketHandler) IsSSLRequestDeny ¶
func (packet *PacketHandler) IsSSLRequestDeny() bool
IsSSLRequestDeny returns true server denied switch to SSL
func (*PacketHandler) IsSimpleQuery ¶
func (packet *PacketHandler) IsSimpleQuery() bool
IsSimpleQuery return true if packet has SimpleQuery type
func (*PacketHandler) Marshal ¶
func (packet *PacketHandler) Marshal() ([]byte, error)
Marshal transforms data row into bytes array it's not marshal message type if it == 0 (if it was first Startup/SSLRequest packet without message type)
func (*PacketHandler) ReadClientPacket ¶
func (packet *PacketHandler) ReadClientPacket() error
ReadClientPacket read and recognize packets that may be sent only from client/frontend.
There are two types of messages: startup and general ones. Due to historical reasons, startup messages have the following format:
[4-byte length] [4-byte tag] [payload...]
On the other hand, general messages have:
[1-byte tag] [4-byte length] [payload...]
Overall, as of today (PostgreSQL 14), the protocol supports following packets, that can be received from the client (Frontend or F), or both the client and the server (Backend) (F&B): ``` | Name | Type | StartsWith | |---------------------|------|-------------------------------| | Bind | F | Byte1('B') || Int32(len) | | CancelRequest | F | int32(16) || Int32(80877102) | | Close | F | Byte1('C') || Int32(len) | | CopyData | F&B | Byte1('d') || Int32(len) | | CopyDone | F&B | Byte1('c') || Int32(len) | | CopyFail | F | Byte1('f') || Int32(len) | | Describe | F | Byte1('D') || Int32(len) | | Execute | F | Byte1('E') || Int32(len) | | Flush | F | Byte1('H') || Int32(len) | | FunctionCall | F | Byte1('F') || Int32(len) | | GSSENCRequest | F | Int32(8) || Int32(80877104) | | GSSResponse | F | Byte1('p') || Int32(len) | | Parse | F | Byte1('P') || Int32(len) | | PasswordMessage | F | Byte1('p') || Int32(len) | | Query | F | Byte1('Q') || Int32(len) | | SASLInitialResponse | F | Byte1('p') || Int32(len) | | SASLResponse | F | Byte1('p') || Int32(len) | | SSLRequest | F | Int32(8) || Int32(80877103) | | StartupMessage | F | Int32(len) || Int32(196608) | | Sync | F | Byte1('S') || Int32(len) | | Terminate | F | Byte1('X') || Int32(len) | ```
Startup message can only be received as first message after connection is established. This fact allows to distinguish which format to parse. If connection is established, and first message is not startup one, this function returns ErrUnsupportedPacketType. If startup message is already received, but then comes a message with unknown format, it would be parsed as a general message with unknown tag.
https://www.postgresql.org/docs/current/static/protocol-message-formats.html
func (*PacketHandler) ReadPacket ¶
func (packet *PacketHandler) ReadPacket() error
ReadPacket read message type and data part of packet
func (*PacketHandler) ReplaceBind ¶
func (packet *PacketHandler) ReplaceBind(bindPacket *BindPacket) error
ReplaceBind update Bind packet with new data, update packet length.
func (*PacketHandler) ReplaceQuery ¶
func (packet *PacketHandler) ReplaceQuery(newQuery string)
ReplaceQuery query in packet with new query and update packet length
func (*PacketHandler) SetParsePacket ¶
func (packet *PacketHandler) SetParsePacket(parsePacket *ParsePacket) error
SetParsePacket replace ParsePacket Use this only if IsParse() is true.
func (*PacketHandler) SetStarted ¶
func (packet *PacketHandler) SetStarted()
SetStarted sets `started` true, which indicates that we should process next packets as general ones
type PacketType ¶
type PacketType int
PacketType describes how to handle a message packet.
const ( SimpleQueryPacket PacketType = iota ParseStatementPacket ParseCompletePacket BindStatementPacket BindCompletePacket DataPacket RowDescriptionPacket ParameterDescriptionPacket ReadyForQueryPacket ExecutePacketType OtherPacket )
Possible PacketType values.
type ParsePacket ¶
type ParsePacket struct {
// contains filtered or unexported fields
}
ParsePacket store data related with Parse postgresql message
func NewParsePacket ¶
func NewParsePacket(data []byte) (*ParsePacket, error)
NewParsePacket parse data and return as ParsePacket or error
func (*ParsePacket) Length ¶
func (packet *ParsePacket) Length() int
Length return total length of packet
func (*ParsePacket) Name ¶
func (packet *ParsePacket) Name() string
Name returns requested prepared statement name. Note that empty string is a valid value indicating unnamed prepared statement.
func (*ParsePacket) QueryString ¶
func (packet *ParsePacket) QueryString() string
QueryString return query as string
func (*ParsePacket) ReplaceQuery ¶
func (packet *ParsePacket) ReplaceQuery(newQuery string)
ReplaceQuery with new query
func (*ParsePacket) Zeroize ¶
func (packet *ParsePacket) Zeroize()
Zeroize sensitive data in the packet.
type PgPortal ¶
type PgPortal struct {
// contains filtered or unexported fields
}
PgPortal is a PostgreSQL Cursor. Cursors are called "portals" in PostgreSQL protocol specs.
func NewPortal ¶
func NewPortal(bind *BindPacket, statement PreparedStatement) *PgPortal
NewPortal makes a new portal.
func (*PgPortal) PreparedStatement ¶
func (p *PgPortal) PreparedStatement() PreparedStatement
PreparedStatement returns the prepared statement this cursor is associated with.
type PgPreparedStatement ¶
type PgPreparedStatement struct {
// contains filtered or unexported fields
}
PgPreparedStatement is a PostgreSQL PreparedStatement.
func NewPreparedStatement ¶
func NewPreparedStatement(name string, text string, stmt *pg_query.ParseResult) *PgPreparedStatement
NewPreparedStatement makes a new prepared statement.
func (*PgPreparedStatement) Name ¶
func (s *PgPreparedStatement) Name() string
Name returns the name of the prepared statement.
func (*PgPreparedStatement) ParamsNum ¶
func (s *PgPreparedStatement) ParamsNum() int
ParamsNum return numbers of prepared statement params
func (*PgPreparedStatement) Query ¶
func (s *PgPreparedStatement) Query() *pg_query.ParseResult
Query returns the prepared query, in its parsed form.
func (*PgPreparedStatement) QueryText ¶
func (s *PgPreparedStatement) QueryText() string
QueryText returns text of the prepared query, as provided by the client.
type PgPreparedStatementRegistry ¶
type PgPreparedStatementRegistry struct {
// contains filtered or unexported fields
}
PgPreparedStatementRegistry is a PostgreSQL PreparedStatementRegistry.
func NewPreparedStatementRegistry ¶
func NewPreparedStatementRegistry() *PgPreparedStatementRegistry
NewPreparedStatementRegistry makes a new empty prepared statement registry.
func (*PgPreparedStatementRegistry) AddCursor ¶
func (r *PgPreparedStatementRegistry) AddCursor(cursor Cursor) error
AddCursor adds a cursor to the registry. If an existing cursor with the same name exists, it is replaced with the new one.
func (*PgPreparedStatementRegistry) AddStatement ¶
func (r *PgPreparedStatementRegistry) AddStatement(statement PreparedStatement) error
AddStatement adds a prepared statement to the registry. If an existing statement with the same name exists, it is replaced with the new one.
func (*PgPreparedStatementRegistry) CursorByName ¶
func (r *PgPreparedStatementRegistry) CursorByName(name string) (Cursor, error)
CursorByName returns a cursor from the registry by its name, if it exists.
func (*PgPreparedStatementRegistry) DeleteCursor ¶
func (r *PgPreparedStatementRegistry) DeleteCursor(name string) error
DeleteCursor removes a portals with given name from the registry. It is not an error to remove nonexistent portals. In this case no error is returned and no action is taken.
func (*PgPreparedStatementRegistry) DeleteStatement ¶
func (r *PgPreparedStatementRegistry) DeleteStatement(name string) error
DeleteStatement removes a statement with given name from the registry. It is not an error to remove nonexistent statements. In this case no error is returned and no action is taken. Removing a prepared statements removes all cursors associated with it.
func (*PgPreparedStatementRegistry) StatementByName ¶
func (r *PgPreparedStatementRegistry) StatementByName(name string) (PreparedStatement, error)
StatementByName returns a prepared statement from the registry by its name, if it exists.
type PgProtocolState ¶
type PgProtocolState struct {
// contains filtered or unexported fields
}
PgProtocolState keeps track of PostgreSQL protocol state.
func NewPgProtocolState ¶
func NewPgProtocolState(registry *PgPreparedStatementRegistry) *PgProtocolState
NewPgProtocolState makes an initial PostgreSQL state, awaiting for queries.
func (*PgProtocolState) HandleClientPacket ¶
func (p *PgProtocolState) HandleClientPacket(packet *PacketHandler) error
HandleClientPacket observes a packet from client to the database, extracts query information from it, and anticipates future database responses.
func (*PgProtocolState) HandleDatabasePacket ¶
func (p *PgProtocolState) HandleDatabasePacket(packet *PacketHandler) error
HandleDatabasePacket observes a packet with database response, extracts useful information from it, and confirms client requests.
func (*PgProtocolState) LastPacketType ¶
func (p *PgProtocolState) LastPacketType() PacketType
LastPacketType returns type of the last seen packet.
type PgProxy ¶
type PgProxy struct { ClientStopResponse chan bool // contains filtered or unexported fields }
PgProxy represents PgSQL database connection between client and database with TLS support
func NewPgProxy ¶
func NewPgProxy(session base.ClientSession, parser *sqlparser.Parser, setting base.ProxySetting) (*PgProxy, error)
NewPgProxy returns new PgProxy
func (*PgProxy) AddClientIDObserver ¶
func (proxy *PgProxy) AddClientIDObserver(observer base.ClientIDObserver)
AddClientIDObserver subscribe new observer for clientID changes
func (*PgProxy) AddQueryObserver ¶
func (proxy *PgProxy) AddQueryObserver(obs postgresql.QueryObserver)
AddQueryObserver implement QueryObservable interface and proxy call to ObserverManager
func (*PgProxy) ProxyClientConnection ¶
func (proxy *PgProxy) ProxyClientConnection(ctx context.Context, errCh chan<- base.ProxyError)
ProxyClientConnection checks every client request using AcraCensor, if request is allowed, sends it to the Pg database
func (*PgProxy) ProxyDatabaseConnection ¶
func (proxy *PgProxy) ProxyDatabaseConnection(ctx context.Context, errCh chan<- base.ProxyError)
ProxyDatabaseConnection process data rows from database
func (*PgProxy) RegisteredObserversCount ¶
RegisteredObserversCount return count of registered observers
func (*PgProxy) SubscribeOnAllColumnsDecryption ¶
func (proxy *PgProxy) SubscribeOnAllColumnsDecryption(subscriber base.DecryptionSubscriber)
SubscribeOnAllColumnsDecryption subscribes for notifications on each column.
func (*PgProxy) Unsubscribe ¶
func (proxy *PgProxy) Unsubscribe(subscriber base.DecryptionSubscriber)
Unsubscribe a subscriber from all notifications.
type PgSQLDataDecoderProcessor ¶
type PgSQLDataDecoderProcessor struct{}
PgSQLDataDecoderProcessor implements processor and decode binary/text values from DB
func NewPgSQLDataDecoderProcessor ¶
func NewPgSQLDataDecoderProcessor() (*PgSQLDataDecoderProcessor, error)
NewPgSQLDataDecoderProcessor return new data decoder from text/binary format from database side
func (*PgSQLDataDecoderProcessor) ID ¶
func (p *PgSQLDataDecoderProcessor) ID() string
ID return name of processor
type PgSQLDataEncoderProcessor ¶
type PgSQLDataEncoderProcessor struct{}
PgSQLDataEncoderProcessor implements processor and encode binary/text values before sending to app
func NewPgSQLDataEncoderProcessor ¶
func NewPgSQLDataEncoderProcessor() (*PgSQLDataEncoderProcessor, error)
NewPgSQLDataEncoderProcessor return new data encoder to text/binary format
func (*PgSQLDataEncoderProcessor) ID ¶
func (p *PgSQLDataEncoderProcessor) ID() string
ID return name of processor
type PreparedStatement ¶
type PreparedStatement interface { Name() string Query() *pg_query.ParseResult QueryText() string ParamsNum() int }
PreparedStatement is a prepared statement, ready to be executed. It can be either a textual SQL statement from "PREPARE", or a database protocol equivalent.
type PreparedStatementsQuery ¶
type PreparedStatementsQuery struct {
// contains filtered or unexported fields
}
PreparedStatementsQuery QueryDataEncryptor process PostgreSQL SQL PreparedStatement
func NewPostgresqlPreparedStatementsQuery ¶
func NewPostgresqlPreparedStatementsQuery(registry *PgPreparedStatementRegistry, queryObserver postgresql.QueryObserver) *PreparedStatementsQuery
NewPostgresqlPreparedStatementsQuery create new QueryDataEncryptor to handle SQL PreparedStatement in the following format `prepare {prepare_statement_name} (params...) as the sql-query` and `execute (values...) {prepare_statement_name}`
func (*PreparedStatementsQuery) ID ¶
func (encryptor *PreparedStatementsQuery) ID() string
ID returns name of this QueryObserver.
func (*PreparedStatementsQuery) OnBind ¶
func (encryptor *PreparedStatementsQuery) OnBind(ctx context.Context, statement *pg_query.ParseResult, values []base.BoundValue) ([]base.BoundValue, bool, error)
OnBind just a stub method of QueryObserver of PreparedStatementsQuery
func (*PreparedStatementsQuery) OnQuery ¶
func (encryptor *PreparedStatementsQuery) OnQuery(ctx context.Context, query postgresql.OnQueryObject) (postgresql.OnQueryObject, bool, error)
OnQuery processes query text before database sees it.