pgx/sasl_initial_response.go
Yuli Khodorkovskiy 5c447ff35d Fix JSON output for SASL{Response,InitialResponse}
Hex encoding the Data field in the SASL responses made debugging SCRAM
more difficult than actually helping.

Before:

F{"Type":"SASLResponse","Data":"633d655377732c723d4d4d4e4e6d666b536f5862694a68385833466d324f2b4d77787354692f4550753052414157484b7a306b7376336c5747392f4d4a5267504d2c703d616742664b533164383937674b4f4a6d4c7171626c49326b6b4a506f2b58354359516c63473458357657343d"}
F{"Type":"SASLInitialResponse","AuthMechanism":"SCRAM-SHA-256","Data":"792c2c6e3d2c723d4d4d4e4e6d666b536f5862694a68385833466d324f2b4d77"}

After:

F{"Type":"SASLResponse","Data":"c=eSws,r=9dR43UQLL1KbrKKl4/QbxjqgVjZYR9mqnx3rFBiI7R/1pp5oeVYMGhXj,p=b2hmuvTvWn2xN0fclm+O4TwLAarRM8xoHSN7jsKDHAU="}
F{"Type":"SASLInitialResponse","AuthMechanism":"SCRAM-SHA-256","Data":"y,,n=,r=9dR43UQLL1KbrKKl4/Qbxjqg"}
2021-10-30 09:08:58 -05:00

95 lines
2.1 KiB
Go

package pgproto3
import (
"bytes"
"encoding/hex"
"encoding/json"
"errors"
"github.com/jackc/pgio"
)
type SASLInitialResponse struct {
AuthMechanism string
Data []byte
}
// Frontend identifies this message as sendable by a PostgreSQL frontend.
func (*SASLInitialResponse) Frontend() {}
// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message
// type identifier and 4 byte message length.
func (dst *SASLInitialResponse) Decode(src []byte) error {
*dst = SASLInitialResponse{}
rp := 0
idx := bytes.IndexByte(src, 0)
if idx < 0 {
return errors.New("invalid SASLInitialResponse")
}
dst.AuthMechanism = string(src[rp:idx])
rp = idx + 1
rp += 4 // The rest of the message is data so we can just skip the size
dst.Data = src[rp:]
return nil
}
// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length.
func (src *SASLInitialResponse) Encode(dst []byte) []byte {
dst = append(dst, 'p')
sp := len(dst)
dst = pgio.AppendInt32(dst, -1)
dst = append(dst, []byte(src.AuthMechanism)...)
dst = append(dst, 0)
dst = pgio.AppendInt32(dst, int32(len(src.Data)))
dst = append(dst, src.Data...)
pgio.SetInt32(dst[sp:], int32(len(dst[sp:])))
return dst
}
// MarshalJSON implements encoding/json.Marshaler.
func (src SASLInitialResponse) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type string
AuthMechanism string
Data string
}{
Type: "SASLInitialResponse",
AuthMechanism: src.AuthMechanism,
Data: string(src.Data),
})
}
// UnmarshalJSON implements encoding/json.Unmarshaler.
func (dst *SASLInitialResponse) UnmarshalJSON(data []byte) error {
// Ignore null, like in the main JSON package.
if string(data) == "null" {
return nil
}
var msg struct {
AuthMechanism string
Data string
}
if err := json.Unmarshal(data, &msg); err != nil {
return err
}
dst.AuthMechanism = msg.AuthMechanism
if msg.Data != "" {
decoded, err := hex.DecodeString(msg.Data)
if err != nil {
return err
}
dst.Data = decoded
}
return nil
}