actions.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. package dataprovider
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "net/url"
  7. "os"
  8. "os/exec"
  9. "path/filepath"
  10. "strings"
  11. "time"
  12. "github.com/drakkan/sftpgo/v2/httpclient"
  13. "github.com/drakkan/sftpgo/v2/logger"
  14. "github.com/drakkan/sftpgo/v2/sdk/plugin"
  15. "github.com/drakkan/sftpgo/v2/sdk/plugin/notifier"
  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. actionObjectAdmin = "admin"
  28. actionObjectAPIKey = "api_key"
  29. actionObjectShare = "share"
  30. )
  31. func executeAction(operation, executor, ip, objectType, objectName string, object plugin.Renderer) {
  32. if plugin.Handler.HasNotifiers() {
  33. plugin.Handler.NotifyProviderEvent(&notifier.ProviderEvent{
  34. Action: operation,
  35. Username: executor,
  36. ObjectType: objectType,
  37. ObjectName: objectName,
  38. IP: ip,
  39. Timestamp: time.Now().UnixNano(),
  40. }, object)
  41. }
  42. if config.Actions.Hook == "" {
  43. return
  44. }
  45. if !util.IsStringInSlice(operation, config.Actions.ExecuteOn) ||
  46. !util.IsStringInSlice(objectType, config.Actions.ExecuteFor) {
  47. return
  48. }
  49. go func() {
  50. dataAsJSON, err := object.RenderAsJSON(operation != operationDelete)
  51. if err != nil {
  52. providerLog(logger.LevelError, "unable to serialize user as JSON for operation %#v: %v", operation, err)
  53. return
  54. }
  55. if strings.HasPrefix(config.Actions.Hook, "http") {
  56. var url *url.URL
  57. url, err := url.Parse(config.Actions.Hook)
  58. if err != nil {
  59. providerLog(logger.LevelError, "Invalid http_notification_url %#v for operation %#v: %v",
  60. config.Actions.Hook, operation, err)
  61. return
  62. }
  63. q := url.Query()
  64. q.Add("action", operation)
  65. q.Add("username", executor)
  66. q.Add("ip", ip)
  67. q.Add("object_type", objectType)
  68. q.Add("object_name", objectName)
  69. q.Add("timestamp", fmt.Sprintf("%v", time.Now().UnixNano()))
  70. url.RawQuery = q.Encode()
  71. startTime := time.Now()
  72. resp, err := httpclient.RetryablePost(url.String(), "application/json", bytes.NewBuffer(dataAsJSON))
  73. respCode := 0
  74. if err == nil {
  75. respCode = resp.StatusCode
  76. resp.Body.Close()
  77. }
  78. providerLog(logger.LevelDebug, "notified operation %#v to URL: %v status code: %v, elapsed: %v err: %v",
  79. operation, url.Redacted(), respCode, time.Since(startTime), err)
  80. } else {
  81. executeNotificationCommand(operation, executor, ip, objectType, objectName, dataAsJSON) //nolint:errcheck // the error is used in test cases only
  82. }
  83. }()
  84. }
  85. func executeNotificationCommand(operation, executor, ip, objectType, objectName string, objectAsJSON []byte) error {
  86. if !filepath.IsAbs(config.Actions.Hook) {
  87. err := fmt.Errorf("invalid notification command %#v", config.Actions.Hook)
  88. logger.Warn(logSender, "", "unable to execute notification command: %v", err)
  89. return err
  90. }
  91. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  92. defer cancel()
  93. cmd := exec.CommandContext(ctx, config.Actions.Hook)
  94. cmd.Env = append(os.Environ(),
  95. fmt.Sprintf("SFTPGO_PROVIDER_ACTION=%v", operation),
  96. fmt.Sprintf("SFTPGO_PROVIDER_OBJECT_TYPE=%v", objectType),
  97. fmt.Sprintf("SFTPGO_PROVIDER_OBJECT_NAME=%v", objectName),
  98. fmt.Sprintf("SFTPGO_PROVIDER_USERNAME=%v", executor),
  99. fmt.Sprintf("SFTPGO_PROVIDER_IP=%v", ip),
  100. fmt.Sprintf("SFTPGO_PROVIDER_TIMESTAMP=%v", util.GetTimeAsMsSinceEpoch(time.Now())),
  101. fmt.Sprintf("SFTPGO_PROVIDER_OBJECT=%v", string(objectAsJSON)))
  102. startTime := time.Now()
  103. err := cmd.Run()
  104. providerLog(logger.LevelDebug, "executed command %#v, elapsed: %v, error: %v", config.Actions.Hook,
  105. time.Since(startTime), err)
  106. return err
  107. }