actions.go 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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/util"
  16. )
  17. const (
  18. // ActionExecutorSelf is used as username for self action, for example a user/admin that updates itself
  19. ActionExecutorSelf = "__self__"
  20. // ActionExecutorSystem is used as username for actions with no explicit executor associated, for example
  21. // adding/updating a user/admin by loading initial data
  22. ActionExecutorSystem = "__system__"
  23. )
  24. const (
  25. actionObjectUser = "user"
  26. actionObjectAdmin = "admin"
  27. actionObjectAPIKey = "api_key"
  28. )
  29. func executeAction(operation, executor, ip, objectType, objectName string, object plugin.Renderer) {
  30. plugin.Handler.NotifyProviderEvent(time.Now(), operation, executor, objectType, objectName, ip, object)
  31. if config.Actions.Hook == "" {
  32. return
  33. }
  34. if !util.IsStringInSlice(operation, config.Actions.ExecuteOn) ||
  35. !util.IsStringInSlice(objectType, config.Actions.ExecuteFor) {
  36. return
  37. }
  38. go func() {
  39. dataAsJSON, err := object.RenderAsJSON(operation != operationDelete)
  40. if err != nil {
  41. providerLog(logger.LevelWarn, "unable to serialize user as JSON for operation %#v: %v", operation, err)
  42. return
  43. }
  44. if strings.HasPrefix(config.Actions.Hook, "http") {
  45. var url *url.URL
  46. url, err := url.Parse(config.Actions.Hook)
  47. if err != nil {
  48. providerLog(logger.LevelWarn, "Invalid http_notification_url %#v for operation %#v: %v", config.Actions.Hook, operation, err)
  49. return
  50. }
  51. q := url.Query()
  52. q.Add("action", operation)
  53. q.Add("username", executor)
  54. q.Add("ip", ip)
  55. q.Add("object_type", objectType)
  56. q.Add("object_name", objectName)
  57. q.Add("timestamp", fmt.Sprintf("%v", util.GetTimeAsMsSinceEpoch(time.Now())))
  58. url.RawQuery = q.Encode()
  59. startTime := time.Now()
  60. resp, err := httpclient.RetryablePost(url.String(), "application/json", bytes.NewBuffer(dataAsJSON))
  61. respCode := 0
  62. if err == nil {
  63. respCode = resp.StatusCode
  64. resp.Body.Close()
  65. }
  66. providerLog(logger.LevelDebug, "notified operation %#v to URL: %v status code: %v, elapsed: %v err: %v",
  67. operation, url.Redacted(), respCode, time.Since(startTime), err)
  68. } else {
  69. executeNotificationCommand(operation, executor, ip, objectType, objectName, dataAsJSON) //nolint:errcheck // the error is used in test cases only
  70. }
  71. }()
  72. }
  73. func executeNotificationCommand(operation, executor, ip, objectType, objectName string, objectAsJSON []byte) error {
  74. if !filepath.IsAbs(config.Actions.Hook) {
  75. err := fmt.Errorf("invalid notification command %#v", config.Actions.Hook)
  76. logger.Warn(logSender, "", "unable to execute notification command: %v", err)
  77. return err
  78. }
  79. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  80. defer cancel()
  81. cmd := exec.CommandContext(ctx, config.Actions.Hook)
  82. cmd.Env = append(os.Environ(),
  83. fmt.Sprintf("SFTPGO_PROVIDER_ACTION=%v", operation),
  84. fmt.Sprintf("SFTPGO_PROVIDER_OBJECT_TYPE=%v", objectType),
  85. fmt.Sprintf("SFTPGO_PROVIDER_OBJECT_NAME=%v", objectName),
  86. fmt.Sprintf("SFTPGO_PROVIDER_USERNAME=%v", executor),
  87. fmt.Sprintf("SFTPGO_PROVIDER_IP=%v", ip),
  88. fmt.Sprintf("SFTPGO_PROVIDER_TIMESTAMP=%v", util.GetTimeAsMsSinceEpoch(time.Now())),
  89. fmt.Sprintf("SFTPGO_PROVIDER_OBJECT=%v", string(objectAsJSON)))
  90. startTime := time.Now()
  91. err := cmd.Run()
  92. providerLog(logger.LevelDebug, "executed command %#v, elapsed: %v, error: %v", config.Actions.Hook,
  93. time.Since(startTime), err)
  94. return err
  95. }