utils.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. package ccq
  2. import (
  3. "context"
  4. "crypto/ecdsa"
  5. "encoding/hex"
  6. "errors"
  7. "fmt"
  8. "net/http"
  9. "time"
  10. "github.com/certusone/wormhole/node/pkg/common"
  11. gossipv1 "github.com/certusone/wormhole/node/pkg/proto/gossip/v1"
  12. "github.com/certusone/wormhole/node/pkg/query"
  13. "github.com/wormhole-foundation/wormhole/sdk/vaa"
  14. "go.uber.org/zap"
  15. ethAbi "github.com/certusone/wormhole/node/pkg/watchers/evm/connectors/ethabi"
  16. ethBind "github.com/ethereum/go-ethereum/accounts/abi/bind"
  17. eth_common "github.com/ethereum/go-ethereum/common"
  18. ethCrypto "github.com/ethereum/go-ethereum/crypto"
  19. ethClient "github.com/ethereum/go-ethereum/ethclient"
  20. ethRpc "github.com/ethereum/go-ethereum/rpc"
  21. "github.com/gagliardetto/solana-go"
  22. )
  23. func FetchCurrentGuardianSet(ctx context.Context, rpcUrl, coreAddr string) (*common.GuardianSet, error) {
  24. ctx, cancel := context.WithTimeout(ctx, time.Second*5)
  25. defer cancel()
  26. ethContract := eth_common.HexToAddress(coreAddr)
  27. rawClient, err := ethRpc.DialContext(ctx, rpcUrl)
  28. if err != nil {
  29. return nil, errors.New("failed to connect to ethereum")
  30. }
  31. client := ethClient.NewClient(rawClient)
  32. caller, err := ethAbi.NewAbiCaller(ethContract, client)
  33. if err != nil {
  34. return nil, errors.New("failed to create caller")
  35. }
  36. currentIndex, err := caller.GetCurrentGuardianSetIndex(&ethBind.CallOpts{Context: ctx})
  37. if err != nil {
  38. return nil, fmt.Errorf("error requesting current guardian set index: %w", err)
  39. }
  40. gs, err := caller.GetGuardianSet(&ethBind.CallOpts{Context: ctx}, currentIndex)
  41. if err != nil {
  42. return nil, fmt.Errorf("error requesting current guardian set value: %w", err)
  43. }
  44. return &common.GuardianSet{
  45. Keys: gs.Keys,
  46. Index: currentIndex,
  47. }, nil
  48. }
  49. // validateRequest verifies that this API key is allowed to do all of the calls in this request. In the case of an error, it returns the HTTP status.
  50. func validateRequest(logger *zap.Logger, env common.Environment, perms *Permissions, signerKey *ecdsa.PrivateKey, apiKey string, qr *gossipv1.SignedQueryRequest) (int, *query.QueryRequest, error) {
  51. permsForUser, exists := perms.GetUserEntry(apiKey)
  52. if !exists {
  53. logger.Debug("invalid api key", zap.String("apiKey", apiKey))
  54. invalidQueryRequestReceived.WithLabelValues("invalid_api_key").Inc()
  55. return http.StatusForbidden, nil, errors.New("invalid api key")
  56. }
  57. // TODO: Should we verify the signatures?
  58. if len(qr.Signature) == 0 {
  59. if !permsForUser.allowUnsigned || signerKey == nil {
  60. logger.Debug("request not signed and unsigned requests not supported for this user",
  61. zap.String("userName", permsForUser.userName),
  62. zap.Bool("allowUnsigned", permsForUser.allowUnsigned),
  63. zap.Bool("signerKeyConfigured", signerKey != nil),
  64. )
  65. invalidQueryRequestReceived.WithLabelValues("request_not_signed").Inc()
  66. return http.StatusBadRequest, nil, errors.New("request not signed")
  67. }
  68. // Sign the request using our key.
  69. var err error
  70. digest := query.QueryRequestDigest(env, qr.QueryRequest)
  71. qr.Signature, err = ethCrypto.Sign(digest.Bytes(), signerKey)
  72. if err != nil {
  73. logger.Debug("failed to sign request", zap.String("userName", permsForUser.userName), zap.Error(err))
  74. invalidQueryRequestReceived.WithLabelValues("failed_to_sign_request").Inc()
  75. return http.StatusInternalServerError, nil, fmt.Errorf("failed to sign request: %w", err)
  76. }
  77. }
  78. var queryRequest query.QueryRequest
  79. err := queryRequest.Unmarshal(qr.QueryRequest)
  80. if err != nil {
  81. logger.Debug("failed to unmarshal request", zap.String("userName", permsForUser.userName), zap.Error(err))
  82. invalidQueryRequestReceived.WithLabelValues("failed_to_unmarshal_request").Inc()
  83. return http.StatusBadRequest, nil, fmt.Errorf("failed to unmarshal request: %w", err)
  84. }
  85. // Make sure the overall query request is sane.
  86. if err := queryRequest.Validate(); err != nil {
  87. logger.Debug("failed to validate request", zap.String("userName", permsForUser.userName), zap.Error(err))
  88. invalidQueryRequestReceived.WithLabelValues("failed_to_validate_request").Inc()
  89. return http.StatusBadRequest, nil, fmt.Errorf("failed to validate request: %w", err)
  90. }
  91. // Make sure they are allowed to make all of the calls that they are asking for.
  92. for _, pcq := range queryRequest.PerChainQueries {
  93. var status int
  94. var err error
  95. switch q := pcq.Query.(type) {
  96. case *query.EthCallQueryRequest:
  97. status, err = validateCallData(logger, permsForUser, "ethCall", pcq.ChainId, q.CallData)
  98. case *query.EthCallByTimestampQueryRequest:
  99. status, err = validateCallData(logger, permsForUser, "ethCallByTimestamp", pcq.ChainId, q.CallData)
  100. case *query.EthCallWithFinalityQueryRequest:
  101. status, err = validateCallData(logger, permsForUser, "ethCallWithFinality", pcq.ChainId, q.CallData)
  102. case *query.SolanaAccountQueryRequest:
  103. status, err = validateSolanaAccountQuery(logger, permsForUser, "solAccount", pcq.ChainId, q)
  104. case *query.SolanaPdaQueryRequest:
  105. status, err = validateSolanaPdaQuery(logger, permsForUser, "solPDA", pcq.ChainId, q)
  106. default:
  107. logger.Debug("unsupported query type", zap.String("userName", permsForUser.userName), zap.Any("type", pcq.Query))
  108. invalidQueryRequestReceived.WithLabelValues("unsupported_query_type").Inc()
  109. return http.StatusBadRequest, nil, errors.New("unsupported query type")
  110. }
  111. if err != nil {
  112. // Metric is pegged below.
  113. return status, nil, err
  114. }
  115. }
  116. logger.Debug("submitting query request", zap.String("userName", permsForUser.userName))
  117. return http.StatusOK, &queryRequest, nil
  118. }
  119. // validateCallData performs verification on all of the call data objects in a query.
  120. func validateCallData(logger *zap.Logger, permsForUser *permissionEntry, callTag string, chainId vaa.ChainID, callData []*query.EthCallData) (int, error) {
  121. for _, cd := range callData {
  122. contractAddress, err := vaa.BytesToAddress(cd.To)
  123. if err != nil {
  124. logger.Debug("failed to parse contract address", zap.String("userName", permsForUser.userName), zap.String("contract", hex.EncodeToString(cd.To)), zap.Error(err))
  125. invalidQueryRequestReceived.WithLabelValues("invalid_contract_address").Inc()
  126. return http.StatusBadRequest, fmt.Errorf("failed to parse contract address: %w", err)
  127. }
  128. if len(cd.Data) < ETH_CALL_SIG_LENGTH {
  129. logger.Debug("eth call data must be at least four bytes", zap.String("userName", permsForUser.userName), zap.String("data", hex.EncodeToString(cd.Data)))
  130. invalidQueryRequestReceived.WithLabelValues("bad_call_data").Inc()
  131. return http.StatusBadRequest, errors.New("eth call data must be at least four bytes")
  132. }
  133. if !permsForUser.allowAnything {
  134. call := hex.EncodeToString(cd.Data[0:ETH_CALL_SIG_LENGTH])
  135. callKey := fmt.Sprintf("%s:%d:%s:%s", callTag, chainId, contractAddress, call)
  136. if _, exists := permsForUser.allowedCalls[callKey]; !exists {
  137. // The call data doesn't exist including the contract address. See if it's covered by a wildcard.
  138. wildCardCallKey := fmt.Sprintf("%s:%d:*:%s", callTag, chainId, call)
  139. if _, exists := permsForUser.allowedCalls[wildCardCallKey]; !exists {
  140. logger.Debug("requested call not authorized", zap.String("userName", permsForUser.userName), zap.String("callKey", callKey))
  141. invalidQueryRequestReceived.WithLabelValues("call_not_authorized").Inc()
  142. return http.StatusBadRequest, fmt.Errorf(`call "%s" not authorized`, callKey)
  143. }
  144. }
  145. }
  146. totalRequestedCallsByChain.WithLabelValues(chainId.String()).Inc()
  147. }
  148. return http.StatusOK, nil
  149. }
  150. // validateSolanaAccountQuery performs verification on a Solana sol_account query.
  151. func validateSolanaAccountQuery(logger *zap.Logger, permsForUser *permissionEntry, callTag string, chainId vaa.ChainID, q *query.SolanaAccountQueryRequest) (int, error) {
  152. if !permsForUser.allowAnything {
  153. for _, acct := range q.Accounts {
  154. callKey := fmt.Sprintf("%s:%d:%s", callTag, chainId, solana.PublicKey(acct).String())
  155. if _, exists := permsForUser.allowedCalls[callKey]; !exists {
  156. logger.Debug("requested call not authorized", zap.String("userName", permsForUser.userName), zap.String("callKey", callKey))
  157. invalidQueryRequestReceived.WithLabelValues("call_not_authorized").Inc()
  158. return http.StatusForbidden, fmt.Errorf(`call "%s" not authorized`, callKey)
  159. }
  160. totalRequestedCallsByChain.WithLabelValues(chainId.String()).Inc()
  161. }
  162. }
  163. return http.StatusOK, nil
  164. }
  165. // validateSolanaPdaQuery performs verification on a Solana sol_account query.
  166. func validateSolanaPdaQuery(logger *zap.Logger, permsForUser *permissionEntry, callTag string, chainId vaa.ChainID, q *query.SolanaPdaQueryRequest) (int, error) {
  167. if !permsForUser.allowAnything {
  168. for _, acct := range q.PDAs {
  169. callKey := fmt.Sprintf("%s:%d:%s", callTag, chainId, solana.PublicKey(acct.ProgramAddress).String())
  170. if _, exists := permsForUser.allowedCalls[callKey]; !exists {
  171. logger.Debug("requested call not authorized", zap.String("userName", permsForUser.userName), zap.String("callKey", callKey))
  172. invalidQueryRequestReceived.WithLabelValues("call_not_authorized").Inc()
  173. return http.StatusForbidden, fmt.Errorf(`call "%s" not authorized`, callKey)
  174. }
  175. totalRequestedCallsByChain.WithLabelValues(chainId.String()).Inc()
  176. }
  177. }
  178. return http.StatusOK, nil
  179. }