Skip to content

Commit

Permalink
refactor: add check to autoswitch authtype in case of scram only (kep…
Browse files Browse the repository at this point in the history
…loy#1616)

* refactor: add check to autoswitch authtype in case of scram only

Signed-off-by: Sarthak160 <[email protected]>

* chore: remove linting warnings

Signed-off-by: Sarthak160 <[email protected]>

* refactor: change if conditions to switch case

Signed-off-by: Sarthak160 <[email protected]>

---------

Signed-off-by: Sarthak160 <[email protected]>
  • Loading branch information
Sarthak160 authored Feb 28, 2024
1 parent 07239c0 commit 28e14bf
Show file tree
Hide file tree
Showing 13 changed files with 191 additions and 273 deletions.
6 changes: 3 additions & 3 deletions pkg/clients/docker/docker_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -537,8 +537,8 @@ func (idc *internalDockerClient) AddNetworkToCompose(dockerComposefilePath, newC
&yaml.Node{
Kind: yaml.MappingNode,
Content: []*yaml.Node{
&yaml.Node{Kind: yaml.ScalarNode, Value: "external"},
&yaml.Node{Kind: yaml.ScalarNode, Value: "true"},
{Kind: yaml.ScalarNode, Value: "external"},
{Kind: yaml.ScalarNode, Value: "true"},
},
},
)
Expand All @@ -560,7 +560,7 @@ func (idc *internalDockerClient) AddNetworkToCompose(dockerComposefilePath, newC
&yaml.Node{
Kind: yaml.SequenceNode,
Content: []*yaml.Node{
&yaml.Node{Kind: yaml.ScalarNode, Value: "keploy-network"},
{Kind: yaml.ScalarNode, Value: "keploy-network"},
},
},
)
Expand Down
2 changes: 1 addition & 1 deletion pkg/graph/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ import (
type graphInterface interface {
Serve(path string, proxyPort uint32, mongoPassword, testReportPath string, generateTestReport bool, Delay uint64, pid, port uint32, lang string, passThroughPorts []uint, apiTimeout uint64, appCmd string, enableTele bool, testFilters map[string][]string)
stopGraphqlServer(http *http.Server)
}
}
1 change: 0 additions & 1 deletion pkg/hooks/ringBufReader.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,6 @@ func socketDataEventCallback(reader *ringbuf.Reader, connectionFactory *connecti
continue
}


data := record.RawSample
if len(data) < eventAttributesSize {
logger.Debug(fmt.Sprintf("Buffer's for SocketDataEvent is smaller (%d) than the minimum required (%d)", len(data), eventAttributesSize))
Expand Down
3 changes: 1 addition & 2 deletions pkg/models/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ test:
coverageReportPath: ""
`


type Config struct {
Record Record `json:"record" yaml:"record"`
Test Test `json:"test" yaml:"test"`
Expand Down Expand Up @@ -103,7 +102,7 @@ type Test struct {
BypassEndpointsRegistry []string `json:"bypassEndpointsRegistry" yaml:"bypassEndpointsRegistry"`
WithCoverage bool `json:"withCoverage" yaml:"withCoverage"` // boolean to capture the coverage in test
CoverageReportPath string `json:"coverageReportPath" yaml:"coverageReportPath"` // directory path to store the coverage files
GenerateTestReport bool `json:"generateTestReport" yaml:"generateTestReport"`
GenerateTestReport bool `json:"generateTestReport" yaml:"generateTestReport"`
IgnoreOrdering bool `json:"ignoreOrdering" yaml:"ignoreOrdering"`
Stubs Stubs `json:"stubs" yaml:"stubs"`
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/models/mock.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,4 @@ const (
type GenericPayload struct {
Origin OriginType `json:"Origin,omitempty" yaml:"origin" bson:"origin,omitempty"`
Message []OutputBinary `json:"Message,omitempty" yaml:"message" bson:"message,omitempty"`
}
}
2 changes: 1 addition & 1 deletion pkg/models/mysql.go
Original file line number Diff line number Diff line change
Expand Up @@ -197,4 +197,4 @@ type AuthSwitchRequestPacket struct {
StatusTag byte `json:"status_tag,omitempty" yaml:"status_tag,omitempty,flow" bson:"status_tag,omitempty"`
PluginName string `json:"plugin_name,omitempty" yaml:"plugin_name,omitempty,flow" bson:"plugin_name,omitempty"`
PluginAuthData string `json:"plugin_authdata,omitempty" yaml:"plugin_authdata,omitempty,flow" bson:"plugin_authdata,omitempty"`
}
}
2 changes: 1 addition & 1 deletion pkg/models/postgres.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ type Frontend struct {
PacketTypes []string `json:"header,omitempty" yaml:"header,omitempty,flow"`
Identfier string `json:"identifier,omitempty" yaml:"identifier,omitempty"`
Length uint32 `json:"length,omitempty" yaml:"length,omitempty"`
Payload string `json:"payload,omitempty" yaml:"payload,omitempty"`
Payload string `json:"payload,omitempty" yaml:"payload,omitempty"`
AuthenticationOk pgproto3.AuthenticationOk `json:"authentication_ok,omitempty" yaml:"authentication_ok,omitempty"`
AuthenticationCleartextPassword pgproto3.AuthenticationCleartextPassword `json:"authentication_cleartext_password,omitempty" yaml:"authentication_cleartext_password,omitempty"`
AuthenticationMD5Password pgproto3.AuthenticationMD5Password `json:"authentication_md5_password,omitempty" yaml:"authentication_md5_password,omitempty"`
Expand Down
2 changes: 1 addition & 1 deletion pkg/models/testcase.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,4 @@ type TestCase struct {

func (tc *TestCase) GetKind() string {
return string(tc.Kind)
}
}
16 changes: 8 additions & 8 deletions pkg/platform/yaml/testReport.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,13 +98,13 @@ func (fe *TestReport) Write(ctx context.Context, path string, doc platform.KindS
data = append(data, d...)

validatedPath, err := util.ValidatePath(filepath.Join(path, readDock.Name+".yaml"))
if err != nil {
return fmt.Errorf("%s failed to validate path: %s", Emoji, err.Error())
}
err = os.WriteFile(validatedPath, data, os.ModePerm)
if err != nil {
return fmt.Errorf("%s failed to write test report in yaml file. error: %s", Emoji, err.Error())
}
if err != nil {
return fmt.Errorf("%s failed to validate path: %s", Emoji, err.Error())
}

err = os.WriteFile(validatedPath, data, os.ModePerm)
if err != nil {
return fmt.Errorf("%s failed to write test report in yaml file. error: %s", Emoji, err.Error())
}
return nil
}
77 changes: 51 additions & 26 deletions pkg/proxy/integrations/postgresParser/postgres_parser.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// Package postgresparser provides functionality for parsing and processing PostgreSQL requests and responses.
package postgresparser

import (
Expand Down Expand Up @@ -61,10 +62,16 @@ func (p *PostgresParser) OutgoingType(buffer []byte) bool {
func (p *PostgresParser) ProcessOutgoing(requestBuffer []byte, clientConn, destConn net.Conn, ctx context.Context) {
switch models.GetMode() {
case models.MODE_RECORD:
encodePostgresOutgoing(requestBuffer, clientConn, destConn, p.hooks, p.logger, ctx)
err := encodePostgresOutgoing(requestBuffer, clientConn, destConn, p.hooks, p.logger, ctx)
if err != nil {
p.logger.Error("failed to encode the outgoing postgres call", zap.Error(err))
}
case models.MODE_TEST:
logger := p.logger.With(zap.Any("Client IP Address", clientConn.RemoteAddr().String()), zap.Any("Client ConnectionID", util.GetNextID()), zap.Any("Destination ConnectionID", util.GetNextID()))
decodePostgresOutgoing(requestBuffer, clientConn, destConn, p.hooks, logger, ctx)
err := decodePostgresOutgoing(requestBuffer, clientConn, destConn, p.hooks, logger, ctx)
if err != nil {
logger.Error("failed to decode the outgoing postgres call", zap.Error(err))
}
default:
p.logger.Info("Invalid mode detected while intercepting outgoing http call", zap.Any("mode", models.GetMode()))
}
Expand Down Expand Up @@ -134,7 +141,10 @@ func encodePostgresOutgoing(requestBuffer []byte, clientConn, destConn net.Conn,

defer utils.HandlePanic()

ReadBuffConn(clientConn, clientBufferChannel, errChannel, logger, h)
err := ReadBuffConn(clientConn, clientBufferChannel, errChannel, logger, h)
if err != nil {
logger.Error("failed to read the packet message in proxy for pg dependency", zap.Error(err))
}
}()
// read response from destination
go func() {
Expand All @@ -143,7 +153,10 @@ func encodePostgresOutgoing(requestBuffer []byte, clientConn, destConn net.Conn,

defer utils.HandlePanic()

ReadBuffConn(destConn, destBufferChannel, errChannel, logger, h)
err := ReadBuffConn(destConn, destBufferChannel, errChannel, logger, h)
if err != nil {
logger.Error("failed to read the packet message in proxy for pg dependency", zap.Error(err))
}
}()

isPreviousChunkRequest := false
Expand All @@ -161,7 +174,7 @@ func encodePostgresOutgoing(requestBuffer []byte, clientConn, destConn net.Conn,
if !isPreviousChunkRequest && len(pgRequests) > 0 && len(pgResponses) > 0 {
metadata := make(map[string]string)
metadata["type"] = "config"
h.AppendMocks(&models.Mock{
err := h.AppendMocks(&models.Mock{
Version: models.GetVersion(),
Name: "mocks",
Kind: models.Postgres,
Expand All @@ -173,11 +186,20 @@ func encodePostgresOutgoing(requestBuffer []byte, clientConn, destConn net.Conn,
Metadata: metadata,
},
}, ctx)
if err != nil {
logger.Error("failed to append the mocks", zap.Error(err))
}
pgRequests = []models.Backend{}
pgResponses = []models.Frontend{}

clientConn.Close()
destConn.Close()
err = clientConn.Close()
if err != nil {
logger.Error("failed to close the client connection", zap.Error(err))
}
err = destConn.Close()
if err != nil {
logger.Error("failed to close the destination connection", zap.Error(err))
}
return nil
}
case buffer := <-clientBufferChannel:
Expand All @@ -193,7 +215,7 @@ func encodePostgresOutgoing(requestBuffer []byte, clientConn, destConn net.Conn,
if !isPreviousChunkRequest && len(pgRequests) > 0 && len(pgResponses) > 0 {
metadata := make(map[string]string)
metadata["type"] = "config"
h.AppendMocks(&models.Mock{
err := h.AppendMocks(&models.Mock{
Version: models.GetVersion(),
Name: "mocks",
Kind: models.Postgres,
Expand All @@ -205,6 +227,9 @@ func encodePostgresOutgoing(requestBuffer []byte, clientConn, destConn net.Conn,
Metadata: metadata,
},
}, ctx)
if err != nil {
logger.Error("failed to append the mocks", zap.Error(err))
}
pgRequests = []models.Backend{}
pgResponses = []models.Frontend{}
}
Expand Down Expand Up @@ -253,7 +278,7 @@ func encodePostgresOutgoing(requestBuffer []byte, clientConn, destConn net.Conn,
i += (5 + pg.BackendWrapper.BodyLen)
}

pg_mock := &models.Backend{
pgMock := &models.Backend{
PacketTypes: pg.BackendWrapper.PacketTypes,
Identfier: "ClientRequest",
Length: uint32(len(requestBuffer)),
Expand Down Expand Up @@ -284,25 +309,25 @@ func encodePostgresOutgoing(requestBuffer []byte, clientConn, destConn net.Conn,
MsgType: pg.BackendWrapper.MsgType,
AuthType: pg.BackendWrapper.AuthType,
}
after_encoded, err := PostgresDecoderBackend(*pg_mock)
afterEncoded, err := PostgresDecoderBackend(*pgMock)
if err != nil {
logger.Debug("failed to decode the response message in proxy for postgres dependency", zap.Error(err))
}

if len(after_encoded) != len(buffer) && pg_mock.PacketTypes[0] != "p" {
logger.Debug("the length of the encoded buffer is not equal to the length of the original buffer", zap.Any("after_encoded", len(after_encoded)), zap.Any("buffer", len(buffer)))
pg_mock.Payload = bufStr
if len(afterEncoded) != len(buffer) && pgMock.PacketTypes[0] != "p" {
logger.Debug("the length of the encoded buffer is not equal to the length of the original buffer", zap.Any("afterEncoded", len(afterEncoded)), zap.Any("buffer", len(buffer)))
pgMock.Payload = bufStr
}
pgRequests = append(pgRequests, *pg_mock)
pgRequests = append(pgRequests, *pgMock)

}

if isStartupPacket(buffer) {
pg_mock := &models.Backend{
pgMock := &models.Backend{
Identfier: "StartupRequest",
Payload: bufStr,
}
pgRequests = append(pgRequests, *pg_mock)
pgRequests = append(pgRequests, *pgMock)
}
}
isPreviousChunkRequest = true
Expand Down Expand Up @@ -348,15 +373,14 @@ func encodePostgresOutgoing(requestBuffer []byte, clientConn, destConn net.Conn,
pg.FrontendWrapper.CommandComplete = *msg.(*pgproto3.CommandComplete)
pg.FrontendWrapper.CommandCompletes = append(pg.FrontendWrapper.CommandCompletes, pg.FrontendWrapper.CommandComplete)
}
if pg.FrontendWrapper.DataRow.RowValues != nil {
if pg.FrontendWrapper.MsgType == 'D' && pg.FrontendWrapper.DataRow.RowValues != nil {
// Create a new slice for each DataRow
valuesCopy := make([]string, len(pg.FrontendWrapper.DataRow.RowValues))
copy(valuesCopy, pg.FrontendWrapper.DataRow.RowValues)

row := pgproto3.DataRow{
RowValues: valuesCopy, // Use the copy of the values
}
// fmt.Println("row is ", row)
dataRows = append(dataRows, row)
}
}
Expand All @@ -369,7 +393,7 @@ func encodePostgresOutgoing(requestBuffer []byte, clientConn, destConn net.Conn,
}

// from here take the msg and append its readabable form to the pgResponses
pg_mock := &models.Frontend{
pgMock := &models.Frontend{
PacketTypes: pg.FrontendWrapper.PacketTypes,
Identfier: "ServerResponse",
Length: uint32(len(requestBuffer)),
Expand Down Expand Up @@ -409,23 +433,24 @@ func encodePostgresOutgoing(requestBuffer []byte, clientConn, destConn net.Conn,
AuthType: pg.FrontendWrapper.AuthType,
}

after_encoded, err := PostgresDecoderFrontend(*pg_mock)
afterEncoded, err := PostgresDecoderFrontend(*pgMock)
if err != nil {
logger.Debug("failed to decode the response message in proxy for postgres dependency", zap.Error(err))
}
if (len(after_encoded) != len(buffer) && pg_mock.PacketTypes[0] != "R") || len(pg_mock.DataRows) > 0 {
logger.Debug("the length of the encoded buffer is not equal to the length of the original buffer", zap.Any("after_encoded", len(after_encoded)), zap.Any("buffer", len(buffer)))
pg_mock.Payload = bufStr

if (len(afterEncoded) != len(buffer) && pgMock.PacketTypes[0] != "R") || len(pgMock.DataRows) > 0 {
logger.Debug("the length of the encoded buffer is not equal to the length of the original buffer", zap.Any("afterEncoded", len(afterEncoded)), zap.Any("buffer", len(buffer)))
pgMock.Payload = bufStr
}
pgResponses = append(pgResponses, *pg_mock)
pgResponses = append(pgResponses, *pgMock)
}

if bufStr == "Tg==" || len(buffer) <= 5 {

pg_mock := &models.Frontend{
pgMock := &models.Frontend{
Payload: bufStr,
}
pgResponses = append(pgResponses, *pg_mock)
pgResponses = append(pgResponses, *pgMock)
}
}

Expand Down
Loading

0 comments on commit 28e14bf

Please sign in to comment.