node.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. // Copyright (C) 2019-2022 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. package dataprovider
  15. import (
  16. "context"
  17. "encoding/json"
  18. "errors"
  19. "fmt"
  20. "io"
  21. "net/http"
  22. "strconv"
  23. "strings"
  24. "time"
  25. "github.com/lestrrat-go/jwx/v2/jwa"
  26. "github.com/lestrrat-go/jwx/v2/jwt"
  27. "github.com/rs/xid"
  28. "github.com/drakkan/sftpgo/v2/internal/httpclient"
  29. "github.com/drakkan/sftpgo/v2/internal/kms"
  30. "github.com/drakkan/sftpgo/v2/internal/logger"
  31. "github.com/drakkan/sftpgo/v2/internal/util"
  32. )
  33. // Supported protocols for connecting to other nodes
  34. const (
  35. NodeProtoHTTP = "http"
  36. NodeProtoHTTPS = "https"
  37. )
  38. const (
  39. // NodeTokenHeader defines the header to use for the node auth token
  40. NodeTokenHeader = "X-SFTPGO-Node"
  41. )
  42. var (
  43. // current node
  44. currentNode *Node
  45. errNoClusterNodes = errors.New("no cluster node defined")
  46. activeNodeTimeDiff = -2 * time.Minute
  47. nodeReqTimeout = 8 * time.Second
  48. )
  49. // NodeConfig defines the node configuration
  50. type NodeConfig struct {
  51. Host string `json:"host" mapstructure:"host"`
  52. Port int `json:"port" mapstructure:"port"`
  53. Proto string `json:"proto" mapstructure:"proto"`
  54. }
  55. func (n *NodeConfig) validate() error {
  56. currentNode = nil
  57. if config.IsShared != 1 {
  58. return nil
  59. }
  60. if n.Host == "" {
  61. return nil
  62. }
  63. currentNode = &Node{
  64. Data: NodeData{
  65. Host: n.Host,
  66. Port: n.Port,
  67. Proto: n.Proto,
  68. },
  69. }
  70. return provider.addNode()
  71. }
  72. // NodeData defines the details to connect to a cluster node
  73. type NodeData struct {
  74. Host string `json:"host"`
  75. Port int `json:"port"`
  76. Proto string `json:"proto"`
  77. Key *kms.Secret `json:"api_key"`
  78. }
  79. func (n *NodeData) validate() error {
  80. if n.Host == "" {
  81. return util.NewValidationError("node host is mandatory")
  82. }
  83. if n.Port < 0 || n.Port > 65535 {
  84. return util.NewValidationError(fmt.Sprintf("invalid node port: %d", n.Port))
  85. }
  86. if n.Proto != NodeProtoHTTP && n.Proto != NodeProtoHTTPS {
  87. return util.NewValidationError(fmt.Sprintf("invalid node proto: %s", n.Proto))
  88. }
  89. n.Key = kms.NewPlainSecret(string(util.GenerateRandomBytes(32)))
  90. n.Key.SetAdditionalData(n.Host)
  91. if err := n.Key.Encrypt(); err != nil {
  92. return fmt.Errorf("unable to encrypt node key: %w", err)
  93. }
  94. return nil
  95. }
  96. // Node defines a cluster node
  97. type Node struct {
  98. Name string `json:"name"`
  99. Data NodeData `json:"data"`
  100. CreatedAt int64 `json:"created_at"`
  101. UpdatedAt int64 `json:"updated_at"`
  102. }
  103. func (n *Node) validate() error {
  104. if n.Name == "" {
  105. n.Name = n.Data.Host
  106. }
  107. return n.Data.validate()
  108. }
  109. func (n *Node) authenticate(token string) (string, string, error) {
  110. if err := n.Data.Key.TryDecrypt(); err != nil {
  111. providerLog(logger.LevelError, "unable to decrypt node key: %v", err)
  112. return "", "", err
  113. }
  114. if token == "" {
  115. return "", "", ErrInvalidCredentials
  116. }
  117. t, err := jwt.Parse([]byte(token), jwt.WithKey(jwa.HS256, []byte(n.Data.Key.GetPayload())), jwt.WithValidate(true))
  118. if err != nil {
  119. return "", "", fmt.Errorf("unable to parse and validate token: %v", err)
  120. }
  121. var adminUsername, role string
  122. if admin, ok := t.Get("admin"); ok {
  123. if val, ok := admin.(string); ok && val != "" {
  124. adminUsername = val
  125. }
  126. }
  127. if adminUsername == "" {
  128. return "", "", errors.New("no admin username associated with node token")
  129. }
  130. if r, ok := t.Get("role"); ok {
  131. if val, ok := r.(string); ok && val != "" {
  132. role = val
  133. }
  134. }
  135. return adminUsername, role, nil
  136. }
  137. // getBaseURL returns the base URL for this node
  138. func (n *Node) getBaseURL() string {
  139. var sb strings.Builder
  140. sb.WriteString(n.Data.Proto)
  141. sb.WriteString("://")
  142. sb.WriteString(n.Data.Host)
  143. if n.Data.Port > 0 {
  144. sb.WriteString(":")
  145. sb.WriteString(strconv.Itoa(n.Data.Port))
  146. }
  147. return sb.String()
  148. }
  149. // generateAuthToken generates a new auth token
  150. func (n *Node) generateAuthToken(username, role string) (string, error) {
  151. if err := n.Data.Key.TryDecrypt(); err != nil {
  152. return "", fmt.Errorf("unable to decrypt node key: %w", err)
  153. }
  154. now := time.Now().UTC()
  155. t := jwt.New()
  156. t.Set("admin", username) //nolint:errcheck
  157. t.Set("role", role) //nolint:errcheck
  158. t.Set(jwt.JwtIDKey, xid.New().String()) //nolint:errcheck
  159. t.Set(jwt.NotBeforeKey, now.Add(-30*time.Second)) //nolint:errcheck
  160. t.Set(jwt.ExpirationKey, now.Add(1*time.Minute)) //nolint:errcheck
  161. payload, err := jwt.Sign(t, jwt.WithKey(jwa.HS256, []byte(n.Data.Key.GetPayload())))
  162. if err != nil {
  163. return "", fmt.Errorf("unable to sign authentication token: %w", err)
  164. }
  165. return string(payload), nil
  166. }
  167. func (n *Node) prepareRequest(ctx context.Context, username, role, relativeURL, method string,
  168. body io.Reader,
  169. ) (*http.Request, error) {
  170. url := fmt.Sprintf("%s%s", n.getBaseURL(), relativeURL)
  171. req, err := http.NewRequestWithContext(ctx, method, url, body)
  172. if err != nil {
  173. return nil, err
  174. }
  175. token, err := n.generateAuthToken(username, role)
  176. if err != nil {
  177. return nil, err
  178. }
  179. req.Header.Set(NodeTokenHeader, fmt.Sprintf("Bearer %s", token))
  180. return req, nil
  181. }
  182. // SendGetRequest sends an HTTP GET request to this node.
  183. // The responseHolder must be a pointer
  184. func (n *Node) SendGetRequest(username, role, relativeURL string, responseHolder any) error {
  185. ctx, cancel := context.WithTimeout(context.Background(), nodeReqTimeout)
  186. defer cancel()
  187. req, err := n.prepareRequest(ctx, username, role, relativeURL, http.MethodGet, nil)
  188. if err != nil {
  189. return err
  190. }
  191. client := httpclient.GetHTTPClient()
  192. defer client.CloseIdleConnections()
  193. resp, err := client.Do(req)
  194. if err != nil {
  195. return fmt.Errorf("unable to send HTTP GET to node %s: %w", n.Name, err)
  196. }
  197. defer resp.Body.Close()
  198. if resp.StatusCode < http.StatusOK || resp.StatusCode > http.StatusNoContent {
  199. return fmt.Errorf("unexpected status code: %d", resp.StatusCode)
  200. }
  201. err = json.NewDecoder(resp.Body).Decode(responseHolder)
  202. if err != nil {
  203. return fmt.Errorf("unable to decode response as json")
  204. }
  205. return nil
  206. }
  207. // SendDeleteRequest sends an HTTP DELETE request to this node
  208. func (n *Node) SendDeleteRequest(username, role, relativeURL string) error {
  209. ctx, cancel := context.WithTimeout(context.Background(), nodeReqTimeout)
  210. defer cancel()
  211. req, err := n.prepareRequest(ctx, username, role, relativeURL, http.MethodDelete, nil)
  212. if err != nil {
  213. return err
  214. }
  215. client := httpclient.GetHTTPClient()
  216. defer client.CloseIdleConnections()
  217. resp, err := client.Do(req)
  218. if err != nil {
  219. return fmt.Errorf("unable to send HTTP DELETE to node %s: %w", n.Name, err)
  220. }
  221. defer resp.Body.Close()
  222. if resp.StatusCode < http.StatusOK || resp.StatusCode > http.StatusNoContent {
  223. return fmt.Errorf("unexpected status code: %d", resp.StatusCode)
  224. }
  225. return nil
  226. }
  227. // AuthenticateNodeToken check the validity of the provided token
  228. func AuthenticateNodeToken(token string) (string, string, error) {
  229. if currentNode == nil {
  230. return "", "", errNoClusterNodes
  231. }
  232. return currentNode.authenticate(token)
  233. }
  234. // GetNodeName returns the node name or an empty string
  235. func GetNodeName() string {
  236. if currentNode == nil {
  237. return ""
  238. }
  239. return currentNode.Name
  240. }