actions.go 5.2 KB

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