actions.go 5.0 KB

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