authentication_sasl.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package pgproto3
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "encoding/json"
  6. "errors"
  7. "github.com/jackc/pgx/v5/internal/pgio"
  8. )
  9. // AuthenticationSASL is a message sent from the backend indicating that SASL authentication is required.
  10. type AuthenticationSASL struct {
  11. AuthMechanisms []string
  12. }
  13. // Backend identifies this message as sendable by the PostgreSQL backend.
  14. func (*AuthenticationSASL) Backend() {}
  15. // Backend identifies this message as an authentication response.
  16. func (*AuthenticationSASL) AuthenticationResponse() {}
  17. // Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message
  18. // type identifier and 4 byte message length.
  19. func (dst *AuthenticationSASL) Decode(src []byte) error {
  20. if len(src) < 4 {
  21. return errors.New("authentication message too short")
  22. }
  23. authType := binary.BigEndian.Uint32(src)
  24. if authType != AuthTypeSASL {
  25. return errors.New("bad auth type")
  26. }
  27. authMechanisms := src[4:]
  28. for len(authMechanisms) > 1 {
  29. idx := bytes.IndexByte(authMechanisms, 0)
  30. if idx == -1 {
  31. return &invalidMessageFormatErr{messageType: "AuthenticationSASL", details: "unterminated string"}
  32. }
  33. dst.AuthMechanisms = append(dst.AuthMechanisms, string(authMechanisms[:idx]))
  34. authMechanisms = authMechanisms[idx+1:]
  35. }
  36. return nil
  37. }
  38. // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length.
  39. func (src *AuthenticationSASL) Encode(dst []byte) ([]byte, error) {
  40. dst, sp := beginMessage(dst, 'R')
  41. dst = pgio.AppendUint32(dst, AuthTypeSASL)
  42. for _, s := range src.AuthMechanisms {
  43. dst = append(dst, []byte(s)...)
  44. dst = append(dst, 0)
  45. }
  46. dst = append(dst, 0)
  47. return finishMessage(dst, sp)
  48. }
  49. // MarshalJSON implements encoding/json.Marshaler.
  50. func (src AuthenticationSASL) MarshalJSON() ([]byte, error) {
  51. return json.Marshal(struct {
  52. Type string
  53. AuthMechanisms []string
  54. }{
  55. Type: "AuthenticationSASL",
  56. AuthMechanisms: src.AuthMechanisms,
  57. })
  58. }