actions.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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. "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. )
  48. var (
  49. actionsConcurrencyGuard = make(chan struct{}, 100)
  50. reservedUsers = []string{ActionExecutorSelf, ActionExecutorSystem}
  51. )
  52. func executeAction(operation, executor, ip, objectType, objectName string, object plugin.Renderer) {
  53. if plugin.Handler.HasNotifiers() {
  54. plugin.Handler.NotifyProviderEvent(&notifier.ProviderEvent{
  55. Action: operation,
  56. Username: executor,
  57. ObjectType: objectType,
  58. ObjectName: objectName,
  59. IP: ip,
  60. Timestamp: time.Now().UnixNano(),
  61. }, object)
  62. }
  63. if fnHandleRuleForProviderEvent != nil {
  64. fnHandleRuleForProviderEvent(operation, executor, ip, objectType, objectName, object)
  65. }
  66. if config.Actions.Hook == "" {
  67. return
  68. }
  69. if !util.Contains(config.Actions.ExecuteOn, operation) ||
  70. !util.Contains(config.Actions.ExecuteFor, objectType) {
  71. return
  72. }
  73. go func() {
  74. actionsConcurrencyGuard <- struct{}{}
  75. defer func() {
  76. <-actionsConcurrencyGuard
  77. }()
  78. dataAsJSON, err := object.RenderAsJSON(operation != operationDelete)
  79. if err != nil {
  80. providerLog(logger.LevelError, "unable to serialize user as JSON for operation %#v: %v", operation, err)
  81. return
  82. }
  83. if strings.HasPrefix(config.Actions.Hook, "http") {
  84. var url *url.URL
  85. url, err := url.Parse(config.Actions.Hook)
  86. if err != nil {
  87. providerLog(logger.LevelError, "Invalid http_notification_url %#v for operation %#v: %v",
  88. config.Actions.Hook, operation, err)
  89. return
  90. }
  91. q := url.Query()
  92. q.Add("action", operation)
  93. q.Add("username", executor)
  94. q.Add("ip", ip)
  95. q.Add("object_type", objectType)
  96. q.Add("object_name", objectName)
  97. q.Add("timestamp", fmt.Sprintf("%d", time.Now().UnixNano()))
  98. url.RawQuery = q.Encode()
  99. startTime := time.Now()
  100. resp, err := httpclient.RetryablePost(url.String(), "application/json", bytes.NewBuffer(dataAsJSON))
  101. respCode := 0
  102. if err == nil {
  103. respCode = resp.StatusCode
  104. resp.Body.Close()
  105. }
  106. providerLog(logger.LevelDebug, "notified operation %#v to URL: %v status code: %v, elapsed: %v err: %v",
  107. operation, url.Redacted(), respCode, time.Since(startTime), err)
  108. } else {
  109. executeNotificationCommand(operation, executor, ip, objectType, objectName, dataAsJSON) //nolint:errcheck // the error is used in test cases only
  110. }
  111. }()
  112. }
  113. func executeNotificationCommand(operation, executor, ip, objectType, objectName string, objectAsJSON []byte) error {
  114. if !filepath.IsAbs(config.Actions.Hook) {
  115. err := fmt.Errorf("invalid notification command %#v", config.Actions.Hook)
  116. logger.Warn(logSender, "", "unable to execute notification command: %v", err)
  117. return err
  118. }
  119. timeout, env, args := command.GetConfig(config.Actions.Hook, command.HookProviderActions)
  120. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  121. defer cancel()
  122. cmd := exec.CommandContext(ctx, config.Actions.Hook, args...)
  123. cmd.Env = append(env,
  124. fmt.Sprintf("SFTPGO_PROVIDER_ACTION=%vs", operation),
  125. fmt.Sprintf("SFTPGO_PROVIDER_OBJECT_TYPE=%s", objectType),
  126. fmt.Sprintf("SFTPGO_PROVIDER_OBJECT_NAME=%s", objectName),
  127. fmt.Sprintf("SFTPGO_PROVIDER_USERNAME=%s", executor),
  128. fmt.Sprintf("SFTPGO_PROVIDER_IP=%s", ip),
  129. fmt.Sprintf("SFTPGO_PROVIDER_TIMESTAMP=%d", util.GetTimeAsMsSinceEpoch(time.Now())),
  130. fmt.Sprintf("SFTPGO_PROVIDER_OBJECT=%s", string(objectAsJSON)))
  131. startTime := time.Now()
  132. err := cmd.Run()
  133. providerLog(logger.LevelDebug, "executed command %#v, elapsed: %v, error: %v", config.Actions.Hook,
  134. time.Since(startTime), err)
  135. return err
  136. }