actions.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. package dataprovider
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "net/url"
  7. "os/exec"
  8. "path/filepath"
  9. "strings"
  10. "time"
  11. "github.com/sftpgo/sdk/plugin/notifier"
  12. "github.com/drakkan/sftpgo/v2/command"
  13. "github.com/drakkan/sftpgo/v2/httpclient"
  14. "github.com/drakkan/sftpgo/v2/logger"
  15. "github.com/drakkan/sftpgo/v2/plugin"
  16. "github.com/drakkan/sftpgo/v2/util"
  17. )
  18. const (
  19. // ActionExecutorSelf is used as username for self action, for example a user/admin that updates itself
  20. ActionExecutorSelf = "__self__"
  21. // ActionExecutorSystem is used as username for actions with no explicit executor associated, for example
  22. // adding/updating a user/admin by loading initial data
  23. ActionExecutorSystem = "__system__"
  24. )
  25. const (
  26. actionObjectUser = "user"
  27. actionObjectGroup = "group"
  28. actionObjectAdmin = "admin"
  29. actionObjectAPIKey = "api_key"
  30. actionObjectShare = "share"
  31. actionObjectEventAction = "event_action"
  32. actionObjectEventRule = "event_rule"
  33. )
  34. func executeAction(operation, executor, ip, objectType, objectName string, object plugin.Renderer) {
  35. if plugin.Handler.HasNotifiers() {
  36. plugin.Handler.NotifyProviderEvent(&notifier.ProviderEvent{
  37. Action: operation,
  38. Username: executor,
  39. ObjectType: objectType,
  40. ObjectName: objectName,
  41. IP: ip,
  42. Timestamp: time.Now().UnixNano(),
  43. }, object)
  44. }
  45. if EventManager.hasProviderEvents() {
  46. EventManager.handleProviderEvent(EventParams{
  47. Name: executor,
  48. ObjectName: objectName,
  49. Event: operation,
  50. Status: 1,
  51. ObjectType: objectType,
  52. IP: ip,
  53. Timestamp: time.Now().UnixNano(),
  54. Object: object,
  55. })
  56. }
  57. if config.Actions.Hook == "" {
  58. return
  59. }
  60. if !util.Contains(config.Actions.ExecuteOn, operation) ||
  61. !util.Contains(config.Actions.ExecuteFor, objectType) {
  62. return
  63. }
  64. go func() {
  65. dataAsJSON, err := object.RenderAsJSON(operation != operationDelete)
  66. if err != nil {
  67. providerLog(logger.LevelError, "unable to serialize user as JSON for operation %#v: %v", operation, err)
  68. return
  69. }
  70. if strings.HasPrefix(config.Actions.Hook, "http") {
  71. var url *url.URL
  72. url, err := url.Parse(config.Actions.Hook)
  73. if err != nil {
  74. providerLog(logger.LevelError, "Invalid http_notification_url %#v for operation %#v: %v",
  75. config.Actions.Hook, operation, err)
  76. return
  77. }
  78. q := url.Query()
  79. q.Add("action", operation)
  80. q.Add("username", executor)
  81. q.Add("ip", ip)
  82. q.Add("object_type", objectType)
  83. q.Add("object_name", objectName)
  84. q.Add("timestamp", fmt.Sprintf("%d", time.Now().UnixNano()))
  85. url.RawQuery = q.Encode()
  86. startTime := time.Now()
  87. resp, err := httpclient.RetryablePost(url.String(), "application/json", bytes.NewBuffer(dataAsJSON))
  88. respCode := 0
  89. if err == nil {
  90. respCode = resp.StatusCode
  91. resp.Body.Close()
  92. }
  93. providerLog(logger.LevelDebug, "notified operation %#v to URL: %v status code: %v, elapsed: %v err: %v",
  94. operation, url.Redacted(), respCode, time.Since(startTime), err)
  95. } else {
  96. executeNotificationCommand(operation, executor, ip, objectType, objectName, dataAsJSON) //nolint:errcheck // the error is used in test cases only
  97. }
  98. }()
  99. }
  100. func executeNotificationCommand(operation, executor, ip, objectType, objectName string, objectAsJSON []byte) error {
  101. if !filepath.IsAbs(config.Actions.Hook) {
  102. err := fmt.Errorf("invalid notification command %#v", config.Actions.Hook)
  103. logger.Warn(logSender, "", "unable to execute notification command: %v", err)
  104. return err
  105. }
  106. timeout, env := command.GetConfig(config.Actions.Hook)
  107. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  108. defer cancel()
  109. cmd := exec.CommandContext(ctx, config.Actions.Hook)
  110. cmd.Env = append(env,
  111. fmt.Sprintf("SFTPGO_PROVIDER_ACTION=%vs", operation),
  112. fmt.Sprintf("SFTPGO_PROVIDER_OBJECT_TYPE=%s", objectType),
  113. fmt.Sprintf("SFTPGO_PROVIDER_OBJECT_NAME=%s", objectName),
  114. fmt.Sprintf("SFTPGO_PROVIDER_USERNAME=%s", executor),
  115. fmt.Sprintf("SFTPGO_PROVIDER_IP=%s", ip),
  116. fmt.Sprintf("SFTPGO_PROVIDER_TIMESTAMP=%d", util.GetTimeAsMsSinceEpoch(time.Now())),
  117. fmt.Sprintf("SFTPGO_PROVIDER_OBJECT=%s", string(objectAsJSON)))
  118. startTime := time.Now()
  119. err := cmd.Run()
  120. providerLog(logger.LevelDebug, "executed command %#v, elapsed: %v, error: %v", config.Actions.Hook,
  121. time.Since(startTime), err)
  122. return err
  123. }