actions.go 4.8 KB

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