base

package
v0.0.0-...-982e07a Latest Latest
Warning

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

Go to latest
Published: Dec 19, 2023 License: Apache-2.0 Imports: 16 Imported by: 5

Documentation

Index

Constants

View Source
const (
	LabelStatus        = "status"
	LabelStatusFail    = "fail"
	LabelStatusSuccess = "success"

	LabelType                 = "type"
	LabelTypeAcraBlock        = "acrablock"
	LabelTypeAcraStruct       = "acrastruct"
	LabelTypeAcraBlockSearch  = "acrablock_searchable"
	LabelTypeAcraStructSearch = "acrastruct_searchable"

	LabelTokenType = "token_type"
)

LabelStatus base constants for prometheus metrics

View Source
const (
	DecryptionDBLabel      = "db"
	DecryptionDBPostgresql = "postgresql"
	DecryptionDBMysql      = "mysql"
)

Labels and values about db type in processing

View Source
const AcraCensorBlockedThisQuery = "AcraCensor blocked this query"

AcraCensorBlockedThisQuery is an error message, that is sent to the user in case of query blockage

View Source
const OldContainerDetectionOn = true

OldContainerDetectionOn is a stub for CLI/buildFlags configuration for containers detection

Variables

View Source
var (
	// AcrastructDecryptionCounter collect decryptions count success/failed
	AcrastructDecryptionCounter = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "acra_acrastruct_decryptions_total",
			Help: "number of AcraStruct decryptions",
		}, []string{LabelStatus})

	// APIEncryptionCounter collect encryptions count success/failed
	APIEncryptionCounter = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "acra_api_encryptions_total",
			Help: "number of encryptions data to AcraStruct",
		}, []string{LabelStatus})
)

Deprecated Metrics

View Source
var (

	// AcraDecryptionCounter collect decryptions count success/failed for type acrablock/acrastruct
	AcraDecryptionCounter = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "acra_decryptions_total",
			Help: "number of decryptions AcraStruct/AcraBlock",
		}, []string{LabelStatus, LabelType})

	// AcraEncryptionCounter collect encryptions count success/failed for type acrablock/acrastruct
	AcraEncryptionCounter = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "acra_encryptions_total",
			Help: "number of encryptions AcraStruct/AcraBlock",
		}, []string{LabelStatus, LabelType})

	// AcraTokenizationCounter collect tokenizations count success/failed for token_type
	AcraTokenizationCounter = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "acra_tokenizations_total",
			Help: "number of tokenizations for token_type",
		}, []string{LabelStatus, LabelTokenType})

	// AcraDetokenizationCounter collect tokenizations count success/failed  for token_type
	AcraDetokenizationCounter = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "acra_detokenizations_total",
			Help: "number of detokenizations for token_type",
		}, []string{LabelStatus, LabelTokenType})

	// ResponseProcessingTimeHistogram collect metrics about response processing time
	ResponseProcessingTimeHistogram = prometheus.NewHistogramVec(prometheus.HistogramOpts{
		Name:    "acraserver_response_processing_seconds",
		Help:    "Time of response processing",
		Buckets: []float64{0.000001, 0.00001, 0.00002, 0.00003, 0.00004, 0.00005, 0.00006, 0.00007, 0.00008, 0.00009, 0.0001, 0.0005, 0.001, 0.005, 0.01, 1, 3, 5, 10},
	}, []string{DecryptionDBLabel})

	// RequestProcessingTimeHistogram collect metrics about request processing time
	RequestProcessingTimeHistogram = prometheus.NewHistogramVec(prometheus.HistogramOpts{
		Name:    "acraserver_request_processing_seconds",
		Help:    "Time of response processing",
		Buckets: []float64{0.000001, 0.00001, 0.00002, 0.00003, 0.00004, 0.00005, 0.00006, 0.00007, 0.00008, 0.00009, 0.0001, 0.0005, 0.001, 0.005, 0.01, 1, 3, 5, 10},
	}, []string{DecryptionDBLabel})
)

Functions

func CheckReadWrite

func CheckReadWrite(n, expectedN int, err error) error

CheckReadWrite check that n == expectedN and err != nil

func EncodedValueContext

func EncodedValueContext(ctx context.Context, value []byte) context.Context

EncodedValueContext save encoded value in the context. Can be used to save encoded value before decoding from database to return as is on decryption failures

func GetEncodedValueFromContext

func GetEncodedValueFromContext(ctx context.Context) ([]byte, bool)

GetEncodedValueFromContext returns encoded value and true if it was saved, otherwise returns nil, false

func IsDecryptedFromContext

func IsDecryptedFromContext(ctx context.Context) bool

IsDecryptedFromContext return true if data was decrypted related to context

func IsErrorConvertedDataTypeFromContext

func IsErrorConvertedDataTypeFromContext(ctx context.Context) bool

IsErrorConvertedDataTypeFromContext return true if data was decrypted related to context

func MarkDecryptedContext

func MarkDecryptedContext(ctx context.Context) context.Context

MarkDecryptedContext save flag in context that data was decrypted

func MarkErrorConvertedDataTypeContext

func MarkErrorConvertedDataTypeContext(ctx context.Context) context.Context

MarkErrorConvertedDataTypeContext save flag in context that was error during data type conversion

func MarkNotDecryptedContext

func MarkNotDecryptedContext(ctx context.Context) context.Context

MarkNotDecryptedContext save flag in context that data wasn't decrypted

func NewEncodingError

func NewEncodingError(column string) error

NewEncodingError returns new EncodingError with specified column

func OnlyDefaultEncryptorSettings

func OnlyDefaultEncryptorSettings(store config.TableSchemaStore) bool

OnlyDefaultEncryptorSettings returns true if config contains settings only for transparent decryption that works by default

func RegisterAcraStructProcessingMetrics

func RegisterAcraStructProcessingMetrics()

RegisterAcraStructProcessingMetrics register in default prometheus registry metrics related with AcraStruct decryption

func RegisterDbProcessingMetrics

func RegisterDbProcessingMetrics()

RegisterDbProcessingMetrics register in default prometheus registry metrics related with processing db requests/responses

func RegisterEncryptionDecryptionProcessingMetrics

func RegisterEncryptionDecryptionProcessingMetrics()

RegisterEncryptionDecryptionProcessingMetrics register in default prometheus registry metrics related with AcraBlock/AcraStruct decryption/encryption

func RegisterTokenizationProcessingMetrics

func RegisterTokenizationProcessingMetrics()

RegisterTokenizationProcessingMetrics register in default prometheus registry metrics related with tokenization/detokenization

func SetAccessContextToContext

func SetAccessContextToContext(ctx context.Context, accessContext *AccessContext) context.Context

SetAccessContextToContext save accessContext to ctx

func SetClientSessionToContext

func SetClientSessionToContext(ctx context.Context, session ClientSession) context.Context

SetClientSessionToContext return context with saved ClientSession

Types

type AccessContext

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

AccessContext store attributes which may be used for access policies and data manipulations

func AccessContextFromContext

func AccessContextFromContext(ctx context.Context) *AccessContext

AccessContextFromContext return AccessContext from ctx or new generated

func NewAccessContext

func NewAccessContext(options ...AccessContextOption) *AccessContext

NewAccessContext create new AccessContext and apply all options. Uses sync.Pool and require releasing by FreeAccessContext

func (*AccessContext) GetAdditionalContext

func (ctx *AccessContext) GetAdditionalContext() []byte

GetAdditionalContext returns additional context

func (*AccessContext) GetClientID

func (ctx *AccessContext) GetClientID() []byte

GetClientID return ClientID

func (*AccessContext) GetColumnInfo

func (ctx *AccessContext) GetColumnInfo() ColumnInfo

GetColumnInfo return ColumnInfo

func (*AccessContext) OnNewClientID

func (ctx *AccessContext) OnNewClientID(clientID []byte)

OnNewClientID set new clientID and implements ClientIDObserver interface

func (*AccessContext) SetClientID

func (ctx *AccessContext) SetClientID(clientID []byte)

SetClientID set new ClientID

func (*AccessContext) SetColumnInfo

func (ctx *AccessContext) SetColumnInfo(info ColumnInfo)

SetColumnInfo set ColumnInfo

type AccessContextOption

type AccessContextOption func(accessContext *AccessContext)

AccessContextOption function used to configure AccessContext struct

func WithClientID

func WithClientID(clientID []byte) AccessContextOption

WithClientID set clientID to AccessContext

type ArrayClientIDObservableManager

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

ArrayClientIDObservableManager store all subscribed observes and call sequentially OnQuery on each observer

func NewArrayClientIDObservableManager

func NewArrayClientIDObservableManager(ctx context.Context) (*ArrayClientIDObservableManager, error)

NewArrayClientIDObservableManager create new ArrayClientIDObservableManager

func (*ArrayClientIDObservableManager) AddClientIDObserver

func (manager *ArrayClientIDObservableManager) AddClientIDObserver(observer ClientIDObserver)

AddClientIDObserver add new subscriber for clientID changes

func (*ArrayClientIDObservableManager) OnNewClientID

func (manager *ArrayClientIDObservableManager) OnNewClientID(clientID []byte)

OnNewClientID pass clientID to subscribers

type ArrayQueryObservableManager

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

ArrayQueryObservableManager store all subscribed observes and call sequentially OnQuery on each observer

func NewArrayQueryObservableManager

func NewArrayQueryObservableManager(ctx context.Context) (*ArrayQueryObservableManager, error)

NewArrayQueryObservableManager create new ArrayQueryObservableManager

func (*ArrayQueryObservableManager) AddQueryObserver

func (manager *ArrayQueryObservableManager) AddQueryObserver(obs QueryObserver)

AddQueryObserver observer to array

func (*ArrayQueryObservableManager) ID

func (manager *ArrayQueryObservableManager) ID() string

ID returns name of this QueryObserver.

func (*ArrayQueryObservableManager) OnBind

func (manager *ArrayQueryObservableManager) OnBind(ctx context.Context, statement sqlparser.Statement, values []BoundValue) ([]BoundValue, bool, error)

OnBind would be called for each added observer to manager.

func (*ArrayQueryObservableManager) OnQuery

OnQuery would be called for each added observer to manager

func (*ArrayQueryObservableManager) RegisteredObserversCount

func (manager *ArrayQueryObservableManager) RegisteredObserversCount() int

RegisteredObserversCount return count of registered observers

type BoundValue

type BoundValue interface {
	Format() BoundValueFormat
	Copy() BoundValue
	SetData(newData []byte, setting config.ColumnEncryptionSetting) error
	GetData(setting config.ColumnEncryptionSetting) ([]byte, error)
	Encode() ([]byte, error)
	GetType() byte
}

BoundValue is a value provided for prepared statement execution. Its exact type and meaning depends on the corresponding query.

type BoundValueFormat

type BoundValueFormat uint16

BoundValueFormat specifies how to interpret the bound data.

const (
	TextFormat BoundValueFormat = iota
	BinaryFormat
)

Supported values of BoundValueFormat.

type Callback

type Callback interface {
	Call() error
}

Callback represents function to call on detecting poison record

type ChainProcessorWrapper

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

ChainProcessorWrapper chain of processors which store all processors and call all of them until one return decrypted data

func NewChainProcessorWrapper

func NewChainProcessorWrapper(processors ...ExtendedDataProcessor) *ChainProcessorWrapper

NewChainProcessorWrapper return wrapped processor

func (*ChainProcessorWrapper) MatchDataSignature

func (d *ChainProcessorWrapper) MatchDataSignature(data []byte) bool

MatchDataSignature call MatchDataSignature for all wrapped processors and return true if any of them return true otherwise false

func (*ChainProcessorWrapper) Process

func (d *ChainProcessorWrapper) Process(inData []byte, ctx *DataProcessorContext) (data []byte, err error)

Process cast ProcessorFunc to DataProcessor interface

type ClientIDObservable

type ClientIDObservable interface {
	AddClientIDObserver(ClientIDObserver)
}

ClientIDObservable used to subscribe for clientID changes

type ClientIDObservableManager

type ClientIDObservableManager interface {
	ClientIDObservable
	ClientIDObserver
}

ClientIDObservableManager used to subscribe for clientID changes and notify about changes

type ClientIDObserver

type ClientIDObserver interface {
	OnNewClientID(clientID []byte)
}

ClientIDObserver used to notify subscribers about changed ClientID in encryption/decryption context

type ClientSession

type ClientSession interface {
	Context() context.Context
	ClientConnection() net.Conn
	DatabaseConnection() net.Conn

	PreparedStatementRegistry() PreparedStatementRegistry
	SetPreparedStatementRegistry(registry PreparedStatementRegistry)

	ProtocolState() interface{}
	SetProtocolState(state interface{})
	GetData(string) (interface{}, bool)
	SetData(string, interface{})
	DeleteData(string)
	HasData(string) bool
}

ClientSession is a connection between the client and the database, mediated by AcraServer.

func ClientSessionFromContext

func ClientSessionFromContext(ctx context.Context) ClientSession

ClientSessionFromContext return saved ClientSession from context or nil

type ColumnDecryptionNotifier

type ColumnDecryptionNotifier interface {
	SubscribeOnAllColumnsDecryption(subscriber DecryptionSubscriber)
	Unsubscribe(DecryptionSubscriber)
}

ColumnDecryptionNotifier interface to subscribe/unsubscribe on OnColumn events

type ColumnDecryptionObserver

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

ColumnDecryptionObserver is a simple ColumnDecryptionNotifier implementation.

func NewColumnDecryptionObserver

func NewColumnDecryptionObserver() ColumnDecryptionObserver

NewColumnDecryptionObserver makes a new observer.

func (*ColumnDecryptionObserver) OnColumnDecryption

func (o *ColumnDecryptionObserver) OnColumnDecryption(ctx context.Context, column int, data []byte) (context.Context, []byte, error)

OnColumnDecryption notifies all subscribers about a change in given column, passing the context and data to them. Returns the data and error returned by subscribers. If a subscriber returns an error, it is immediately returned and other subscribers are not notified.

func (*ColumnDecryptionObserver) SubscribeOnAllColumnsDecryption

func (o *ColumnDecryptionObserver) SubscribeOnAllColumnsDecryption(subscriber DecryptionSubscriber)

SubscribeOnAllColumnsDecryption subscribes for notifications on each column.

func (*ColumnDecryptionObserver) Unsubscribe

func (o *ColumnDecryptionObserver) Unsubscribe(subscriber DecryptionSubscriber)

Unsubscribe a subscriber from all notifications.

type ColumnInfo

type ColumnInfo interface {
	Index() int
	Alias() string
	IsBinaryFormat() bool
	DataBinarySize() int
	DataBinaryType() byte
	OriginBinaryType() byte
}

ColumnInfo interface describe available metadata for column

func ColumnInfoFromContext

func ColumnInfoFromContext(ctx context.Context) (ColumnInfo, bool)

ColumnInfoFromContext return ColumnInfo and true if was assigned, otherwise empty ColumnInfo and false

func NewColumnInfo

func NewColumnInfo(index int, alias string, binaryFormat bool, size int, dataType, originType byte) ColumnInfo

NewColumnInfo return ColumnInfo implementation for metadata

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 DataProcessor

type DataProcessor interface {
	Process(data []byte, context *DataProcessorContext) ([]byte, error)
}

DataProcessor for data from database with AcraStructs

type DataProcessorContext

type DataProcessorContext struct {
	Keystore keystore.DataEncryptorKeyStore
	Context  context.Context
}

DataProcessorContext store data for DataProcessor

func NewDataProcessorContext

func NewDataProcessorContext(keystore keystore.DataEncryptorKeyStore) *DataProcessorContext

NewDataProcessorContext return context with initialized static data

func (*DataProcessorContext) UseContext

func (ctx *DataProcessorContext) UseContext(newContext context.Context) *DataProcessorContext

UseContext replace context and return itself

type DecryptProcessor

type DecryptProcessor struct{}

DecryptProcessor default implementation of DataProcessor with AcraStruct decryption

func (DecryptProcessor) MatchDataSignature

func (DecryptProcessor) MatchDataSignature(data []byte) bool

MatchDataSignature return true if data has valid AcraStruct signature

func (DecryptProcessor) Process

func (p DecryptProcessor) Process(data []byte, context *DataProcessorContext) ([]byte, error)

Process implement DataProcessor with AcraStruct decryption

type DecryptionSubscriber

type DecryptionSubscriber interface {
	OnColumn(context.Context, []byte) (context.Context, []byte, error)
	ID() string
}

DecryptionSubscriber interface to subscribe on column's data in db responses

type EncodingError

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

EncodingError is returned from encoding handlers when some failure occurs. This error should be sent to the user directly, so it needs to be own type to be distinguishable.

func (*EncodingError) Error

func (e *EncodingError) Error() string

func (*EncodingError) Is

func (e *EncodingError) Is(err error) bool

Is checks if err is the same as target error. It checks the type and the `.column` field. Used in tests to provide functionality of `errors.Is`

type EncodingValue

type EncodingValue interface {
	// AssBinary returns value encoded in a binary format
	AsBinary() []byte
	// AsText returns value encoded in a text format
	AsText() []byte
}

EncodingValue represents a (possibly parsed and prepared) value that is ready to be encoded

type EncodingValueFactory

type EncodingValueFactory interface {
	// NewStringValue creates a value that encodes as a str
	NewStringValue(str []byte) EncodingValue
	// NewBytesValue creates a value that encodes as bytes
	NewBytesValue(bytes []byte) EncodingValue
	// NewInt32Value creates a value that encodes as int32
	NewInt32Value(intVal int32, strVal []byte) EncodingValue
	// NewInt64Value creates a value that encodes as int64
	NewInt64Value(intVal int64, strVal []byte) EncodingValue
}

EncodingValueFactory represents a factory that produces ready for encoding value.

type ExtendedDataProcessor

type ExtendedDataProcessor interface {
	DataProcessor
	MatchDataSignature([]byte) bool
}

ExtendedDataProcessor extended with MatchDataSignature method to filter incoming data and skip extra processing

type OnQueryObject

type OnQueryObject interface {
	Statement() (sqlparser.Statement, error)
	Query() string
}

OnQueryObject interface for result of OnQuery call

func NewOnQueryObjectFromQuery

func NewOnQueryObjectFromQuery(query string, parser *sqlparser.Parser) OnQueryObject

NewOnQueryObjectFromQuery return OnQueryObject with query string as value

func NewOnQueryObjectFromStatement

func NewOnQueryObjectFromStatement(stmt sqlparser.Statement, parser *sqlparser.Parser) OnQueryObject

NewOnQueryObjectFromStatement return OnQueryObject with Statement as value

type PoisonRecordCallbackStorage

type PoisonRecordCallbackStorage interface {
	Callback
	AddCallback(callback Callback)
	HasCallbacks() bool
}

PoisonRecordCallbackStorage stores all callbacks, on Call iterates and calls each callbacks until error or end of iterating

type PreparedStatement

type PreparedStatement interface {
	Name() string
	Query() sqlparser.Statement
	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 PreparedStatementRegistry

type PreparedStatementRegistry interface {
	AddStatement(statement PreparedStatement) error
	DeleteStatement(name string) error
	StatementByName(name string) (PreparedStatement, error)

	AddCursor(cursor Cursor) error
	DeleteCursor(name string) error
	CursorByName(name string) (Cursor, error)
}

PreparedStatementRegistry keeps track of active prepared statements and cursors within a ClientSession.

type ProcessorFunc

type ProcessorFunc func([]byte, *DataProcessorContext) ([]byte, error)

ProcessorFunc cast function to cast function as DataProcessor

func (ProcessorFunc) Process

func (f ProcessorFunc) Process(data []byte, ctx *DataProcessorContext) ([]byte, error)

Process cast ProcessorFunc to DataProcessor interface

type ProcessorWrapper

type ProcessorWrapper interface {
	Wrap(DataProcessor) DataProcessor
}

ProcessorWrapper interface for wrappers of DataProcessor

type Proxy

type Proxy interface {
	QueryObservable
	ClientIDObservable
	ProxyClientConnection(context.Context, chan<- ProxyError)
	ProxyDatabaseConnection(context.Context, chan<- ProxyError)
}

Proxy interface to process client's requests to database and responses

type ProxyError

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

ProxyError custom error type for handling all related errors on Client/DB proxies

func NewClientProxyError

func NewClientProxyError(err error) ProxyError

NewClientProxyError construct ProxyError object with Client interrupt side

func NewDBProxyError

func NewDBProxyError(err error) ProxyError

NewDBProxyError construct ProxyError object with DB interrupt side

func (ProxyError) Error

func (p ProxyError) Error() string

func (ProxyError) InterruptSide

func (p ProxyError) InterruptSide() string

InterruptSide return interruption side where error happened

func (ProxyError) Unwrap

func (p ProxyError) Unwrap() error

Unwrap return the source error

type ProxyFactory

type ProxyFactory interface {
	New(clientID []byte, clientSession ClientSession) (Proxy, error)
}

ProxyFactory create new Proxy for specific database

type ProxySetting

type ProxySetting interface {
	PoisonRecordCallbackStorage() PoisonRecordCallbackStorage
	SQLParser() *sqlparser.Parser
	KeyStore() keystore.DecryptionKeyStore
	TableSchemaStore() config.TableSchemaStore
	Censor() acracensor.AcraCensorInterface
	TLSConnectionWrapper() TLSConnectionWrapper
}

ProxySetting provide data access methods for proxy factories

func NewProxySetting

NewProxySetting return new ProxySetting implementation with data from params

type QueryObservable

type QueryObservable interface {
	AddQueryObserver(QueryObserver)
	RegisteredObserversCount() int
}

QueryObservable used to handle subscribers for new incoming queries

type QueryObserver

type QueryObserver interface {
	ID() string
	// Simple queries and prepared statements during preparation stage. SQL is modifiable.
	OnQuery(ctx context.Context, data OnQueryObject) (OnQueryObject, bool, error)
	// Prepared statement parameters during execution stage. Parameter values are modifiable.
	OnBind(ctx context.Context, statement sqlparser.Statement, values []BoundValue) ([]BoundValue, bool, error)
}

QueryObserver observes database queries and is able to modify them. Methods should return "true" as their second bool result if the data has been modified.

type QueryObserverManager

type QueryObserverManager interface {
	QueryObserver
	QueryObservable
}

QueryObserverManager interface for observer aggregations

type TLSConnectionWrapper

type TLSConnectionWrapper interface {
	WrapDBConnection(ctx context.Context, conn net.Conn) (net.Conn, error)
	WrapClientConnection(ctx context.Context, conn net.Conn) (wrappedConnection net.Conn, clientID []byte, err error)
	UseConnectionClientID() bool
}

TLSConnectionWrapper used by proxy to wrap raw connections to TLS when intercepts client/database request about switching to TLS Reuse network.ConnectionWrapper to explicitly force TLS usage by name

func NewTLSConnectionWrapper

func NewTLSConnectionWrapper(useClientID bool, wrapper network.ConnectionWrapper) TLSConnectionWrapper

NewTLSConnectionWrapper return wrapper over network.ConnectionWrapper to implement TLSConnectionWrapper interface

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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