node.go 7.7 KB

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