actions.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  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. "fmt"
  19. "net/url"
  20. "os/exec"
  21. "path/filepath"
  22. "strings"
  23. "time"
  24. "github.com/sftpgo/sdk/plugin/notifier"
  25. "github.com/drakkan/sftpgo/v2/internal/command"
  26. "github.com/drakkan/sftpgo/v2/internal/httpclient"
  27. "github.com/drakkan/sftpgo/v2/internal/logger"
  28. "github.com/drakkan/sftpgo/v2/internal/plugin"
  29. "github.com/drakkan/sftpgo/v2/internal/util"
  30. )
  31. const (
  32. // ActionExecutorSelf is used as username for self action, for example a user/admin that updates itself
  33. ActionExecutorSelf = "__self__"
  34. // ActionExecutorSystem is used as username for actions with no explicit executor associated, for example
  35. // adding/updating a user/admin by loading initial data
  36. ActionExecutorSystem = "__system__"
  37. )
  38. const (
  39. actionObjectUser = "user"
  40. actionObjectFolder = "folder"
  41. actionObjectGroup = "group"
  42. actionObjectAdmin = "admin"
  43. actionObjectAPIKey = "api_key"
  44. actionObjectShare = "share"
  45. actionObjectEventAction = "event_action"
  46. actionObjectEventRule = "event_rule"
  47. actionObjectRole = "role"
  48. actionObjectIPListEntry = "ip_list_entry"
  49. actionObjectConfigs = "configs"
  50. )
  51. var (
  52. actionsConcurrencyGuard = make(chan struct{}, 100)
  53. reservedUsers = []string{ActionExecutorSelf, ActionExecutorSystem}
  54. )
  55. func executeAction(operation, executor, ip, objectType, objectName, role string, object plugin.Renderer) {
  56. if plugin.Handler.HasNotifiers() {
  57. plugin.Handler.NotifyProviderEvent(&notifier.ProviderEvent{
  58. Action: operation,
  59. Username: executor,
  60. ObjectType: objectType,
  61. ObjectName: objectName,
  62. IP: ip,
  63. Role: role,
  64. Timestamp: time.Now().UnixNano(),
  65. }, object)
  66. }
  67. if fnHandleRuleForProviderEvent != nil {
  68. fnHandleRuleForProviderEvent(operation, executor, ip, objectType, objectName, role, object)
  69. }
  70. if config.Actions.Hook == "" {
  71. return
  72. }
  73. if !util.Contains(config.Actions.ExecuteOn, operation) ||
  74. !util.Contains(config.Actions.ExecuteFor, objectType) {
  75. return
  76. }
  77. go func() {
  78. actionsConcurrencyGuard <- struct{}{}
  79. defer func() {
  80. <-actionsConcurrencyGuard
  81. }()
  82. dataAsJSON, err := object.RenderAsJSON(operation != operationDelete)
  83. if err != nil {
  84. providerLog(logger.LevelError, "unable to serialize user as JSON for operation %q: %v", operation, err)
  85. return
  86. }
  87. if strings.HasPrefix(config.Actions.Hook, "http") {
  88. var url *url.URL
  89. url, err := url.Parse(config.Actions.Hook)
  90. if err != nil {
  91. providerLog(logger.LevelError, "Invalid http_notification_url %q for operation %q: %v",
  92. config.Actions.Hook, operation, err)
  93. return
  94. }
  95. q := url.Query()
  96. q.Add("action", operation)
  97. q.Add("username", executor)
  98. q.Add("ip", ip)
  99. q.Add("object_type", objectType)
  100. q.Add("object_name", objectName)
  101. if role != "" {
  102. q.Add("role", role)
  103. }
  104. q.Add("timestamp", fmt.Sprintf("%d", time.Now().UnixNano()))
  105. url.RawQuery = q.Encode()
  106. startTime := time.Now()
  107. resp, err := httpclient.RetryablePost(url.String(), "application/json", bytes.NewBuffer(dataAsJSON))
  108. respCode := 0
  109. if err == nil {
  110. respCode = resp.StatusCode
  111. resp.Body.Close()
  112. }
  113. providerLog(logger.LevelDebug, "notified operation %q to URL: %s status code: %d, elapsed: %s err: %v",
  114. operation, url.Redacted(), respCode, time.Since(startTime), err)
  115. return
  116. }
  117. executeNotificationCommand(operation, executor, ip, objectType, objectName, role, dataAsJSON) //nolint:errcheck // the error is used in test cases only
  118. }()
  119. }
  120. func executeNotificationCommand(operation, executor, ip, objectType, objectName, role string, objectAsJSON []byte) error {
  121. if !filepath.IsAbs(config.Actions.Hook) {
  122. err := fmt.Errorf("invalid notification command %q", config.Actions.Hook)
  123. logger.Warn(logSender, "", "unable to execute notification command: %v", err)
  124. return err
  125. }
  126. timeout, env, args := command.GetConfig(config.Actions.Hook, command.HookProviderActions)
  127. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  128. defer cancel()
  129. cmd := exec.CommandContext(ctx, config.Actions.Hook, args...)
  130. cmd.Env = append(env,
  131. fmt.Sprintf("SFTPGO_PROVIDER_ACTION=%vs", operation),
  132. fmt.Sprintf("SFTPGO_PROVIDER_OBJECT_TYPE=%s", objectType),
  133. fmt.Sprintf("SFTPGO_PROVIDER_OBJECT_NAME=%s", objectName),
  134. fmt.Sprintf("SFTPGO_PROVIDER_USERNAME=%s", executor),
  135. fmt.Sprintf("SFTPGO_PROVIDER_IP=%s", ip),
  136. fmt.Sprintf("SFTPGO_PROVIDER_ROLE=%s", role),
  137. fmt.Sprintf("SFTPGO_PROVIDER_TIMESTAMP=%d", util.GetTimeAsMsSinceEpoch(time.Now())),
  138. fmt.Sprintf("SFTPGO_PROVIDER_OBJECT=%s", string(objectAsJSON)))
  139. startTime := time.Now()
  140. err := cmd.Run()
  141. providerLog(logger.LevelDebug, "executed command %q, elapsed: %s, error: %v", config.Actions.Hook,
  142. time.Since(startTime), err)
  143. return err
  144. }