actions.go 5.3 KB

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