actions_test.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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 common
  15. import (
  16. "errors"
  17. "fmt"
  18. "os"
  19. "os/exec"
  20. "path/filepath"
  21. "runtime"
  22. "testing"
  23. "github.com/lithammer/shortuuid/v3"
  24. "github.com/rs/xid"
  25. "github.com/sftpgo/sdk"
  26. "github.com/sftpgo/sdk/plugin/notifier"
  27. "github.com/stretchr/testify/assert"
  28. "github.com/drakkan/sftpgo/v2/dataprovider"
  29. "github.com/drakkan/sftpgo/v2/plugin"
  30. "github.com/drakkan/sftpgo/v2/vfs"
  31. )
  32. func TestNewActionNotification(t *testing.T) {
  33. user := &dataprovider.User{
  34. BaseUser: sdk.BaseUser{
  35. Username: "username",
  36. },
  37. }
  38. user.FsConfig.Provider = sdk.LocalFilesystemProvider
  39. user.FsConfig.S3Config = vfs.S3FsConfig{
  40. BaseS3FsConfig: sdk.BaseS3FsConfig{
  41. Bucket: "s3bucket",
  42. Endpoint: "endpoint",
  43. },
  44. }
  45. user.FsConfig.GCSConfig = vfs.GCSFsConfig{
  46. BaseGCSFsConfig: sdk.BaseGCSFsConfig{
  47. Bucket: "gcsbucket",
  48. },
  49. }
  50. user.FsConfig.AzBlobConfig = vfs.AzBlobFsConfig{
  51. BaseAzBlobFsConfig: sdk.BaseAzBlobFsConfig{
  52. Container: "azcontainer",
  53. Endpoint: "azendpoint",
  54. },
  55. }
  56. user.FsConfig.SFTPConfig = vfs.SFTPFsConfig{
  57. BaseSFTPFsConfig: sdk.BaseSFTPFsConfig{
  58. Endpoint: "sftpendpoint",
  59. },
  60. }
  61. sessionID := xid.New().String()
  62. a := newActionNotification(user, operationDownload, "path", "vpath", "target", "", "", ProtocolSFTP, "", sessionID,
  63. 123, 0, errors.New("fake error"))
  64. assert.Equal(t, user.Username, a.Username)
  65. assert.Equal(t, 0, len(a.Bucket))
  66. assert.Equal(t, 0, len(a.Endpoint))
  67. assert.Equal(t, 2, a.Status)
  68. user.FsConfig.Provider = sdk.S3FilesystemProvider
  69. a = newActionNotification(user, operationDownload, "path", "vpath", "target", "", "", ProtocolSSH, "", sessionID,
  70. 123, 0, nil)
  71. assert.Equal(t, "s3bucket", a.Bucket)
  72. assert.Equal(t, "endpoint", a.Endpoint)
  73. assert.Equal(t, 1, a.Status)
  74. user.FsConfig.Provider = sdk.GCSFilesystemProvider
  75. a = newActionNotification(user, operationDownload, "path", "vpath", "target", "", "", ProtocolSCP, "", sessionID,
  76. 123, 0, ErrQuotaExceeded)
  77. assert.Equal(t, "gcsbucket", a.Bucket)
  78. assert.Equal(t, 0, len(a.Endpoint))
  79. assert.Equal(t, 3, a.Status)
  80. user.FsConfig.Provider = sdk.AzureBlobFilesystemProvider
  81. a = newActionNotification(user, operationDownload, "path", "vpath", "target", "", "", ProtocolSCP, "", sessionID,
  82. 123, 0, nil)
  83. assert.Equal(t, "azcontainer", a.Bucket)
  84. assert.Equal(t, "azendpoint", a.Endpoint)
  85. assert.Equal(t, 1, a.Status)
  86. a = newActionNotification(user, operationDownload, "path", "vpath", "target", "", "", ProtocolSCP, "", sessionID,
  87. 123, os.O_APPEND, nil)
  88. assert.Equal(t, "azcontainer", a.Bucket)
  89. assert.Equal(t, "azendpoint", a.Endpoint)
  90. assert.Equal(t, 1, a.Status)
  91. assert.Equal(t, os.O_APPEND, a.OpenFlags)
  92. user.FsConfig.Provider = sdk.SFTPFilesystemProvider
  93. a = newActionNotification(user, operationDownload, "path", "vpath", "target", "", "", ProtocolSFTP, "", sessionID,
  94. 123, 0, nil)
  95. assert.Equal(t, "sftpendpoint", a.Endpoint)
  96. }
  97. func TestActionHTTP(t *testing.T) {
  98. actionsCopy := Config.Actions
  99. Config.Actions = ProtocolActions{
  100. ExecuteOn: []string{operationDownload},
  101. Hook: fmt.Sprintf("http://%v", httpAddr),
  102. }
  103. user := &dataprovider.User{
  104. BaseUser: sdk.BaseUser{
  105. Username: "username",
  106. },
  107. }
  108. a := newActionNotification(user, operationDownload, "path", "vpath", "target", "", "", ProtocolSFTP, "",
  109. xid.New().String(), 123, 0, nil)
  110. err := actionHandler.Handle(a)
  111. assert.NoError(t, err)
  112. Config.Actions.Hook = "http://invalid:1234"
  113. err = actionHandler.Handle(a)
  114. assert.Error(t, err)
  115. Config.Actions.Hook = fmt.Sprintf("http://%v/404", httpAddr)
  116. err = actionHandler.Handle(a)
  117. if assert.Error(t, err) {
  118. assert.EqualError(t, err, errUnexpectedHTTResponse.Error())
  119. }
  120. Config.Actions = actionsCopy
  121. }
  122. func TestActionCMD(t *testing.T) {
  123. if runtime.GOOS == osWindows {
  124. t.Skip("this test is not available on Windows")
  125. }
  126. actionsCopy := Config.Actions
  127. hookCmd, err := exec.LookPath("true")
  128. assert.NoError(t, err)
  129. Config.Actions = ProtocolActions{
  130. ExecuteOn: []string{operationDownload},
  131. Hook: hookCmd,
  132. }
  133. user := &dataprovider.User{
  134. BaseUser: sdk.BaseUser{
  135. Username: "username",
  136. },
  137. }
  138. sessionID := shortuuid.New()
  139. a := newActionNotification(user, operationDownload, "path", "vpath", "target", "", "", ProtocolSFTP, "", sessionID,
  140. 123, 0, nil)
  141. err = actionHandler.Handle(a)
  142. assert.NoError(t, err)
  143. c := NewBaseConnection("id", ProtocolSFTP, "", "", *user)
  144. ExecuteActionNotification(c, OperationSSHCmd, "path", "vpath", "target", "vtarget", "sha1sum", 0, nil)
  145. ExecuteActionNotification(c, operationDownload, "path", "vpath", "", "", "", 0, nil)
  146. Config.Actions = actionsCopy
  147. }
  148. func TestWrongActions(t *testing.T) {
  149. actionsCopy := Config.Actions
  150. badCommand := "/bad/command"
  151. if runtime.GOOS == osWindows {
  152. badCommand = "C:\\bad\\command"
  153. }
  154. Config.Actions = ProtocolActions{
  155. ExecuteOn: []string{operationUpload},
  156. Hook: badCommand,
  157. }
  158. user := &dataprovider.User{
  159. BaseUser: sdk.BaseUser{
  160. Username: "username",
  161. },
  162. }
  163. a := newActionNotification(user, operationUpload, "", "", "", "", "", ProtocolSFTP, "", xid.New().String(),
  164. 123, 0, nil)
  165. err := actionHandler.Handle(a)
  166. assert.Error(t, err, "action with bad command must fail")
  167. a.Action = operationDelete
  168. err = actionHandler.Handle(a)
  169. assert.EqualError(t, err, errUnconfiguredAction.Error())
  170. Config.Actions.Hook = "http://foo\x7f.com/"
  171. a.Action = operationUpload
  172. err = actionHandler.Handle(a)
  173. assert.Error(t, err, "action with bad url must fail")
  174. Config.Actions.Hook = ""
  175. err = actionHandler.Handle(a)
  176. if assert.Error(t, err) {
  177. assert.EqualError(t, err, errNoHook.Error())
  178. }
  179. Config.Actions.Hook = "relative path"
  180. err = actionHandler.Handle(a)
  181. if assert.Error(t, err) {
  182. assert.EqualError(t, err, fmt.Sprintf("invalid notification command %#v", Config.Actions.Hook))
  183. }
  184. Config.Actions = actionsCopy
  185. }
  186. func TestPreDeleteAction(t *testing.T) {
  187. if runtime.GOOS == osWindows {
  188. t.Skip("this test is not available on Windows")
  189. }
  190. actionsCopy := Config.Actions
  191. hookCmd, err := exec.LookPath("true")
  192. assert.NoError(t, err)
  193. Config.Actions = ProtocolActions{
  194. ExecuteOn: []string{operationPreDelete},
  195. Hook: hookCmd,
  196. }
  197. homeDir := filepath.Join(os.TempDir(), "test_user")
  198. err = os.MkdirAll(homeDir, os.ModePerm)
  199. assert.NoError(t, err)
  200. user := dataprovider.User{
  201. BaseUser: sdk.BaseUser{
  202. Username: "username",
  203. HomeDir: homeDir,
  204. },
  205. }
  206. user.Permissions = make(map[string][]string)
  207. user.Permissions["/"] = []string{dataprovider.PermAny}
  208. fs := vfs.NewOsFs("id", homeDir, "")
  209. c := NewBaseConnection("id", ProtocolSFTP, "", "", user)
  210. testfile := filepath.Join(user.HomeDir, "testfile")
  211. err = os.WriteFile(testfile, []byte("test"), os.ModePerm)
  212. assert.NoError(t, err)
  213. info, err := os.Stat(testfile)
  214. assert.NoError(t, err)
  215. err = c.RemoveFile(fs, testfile, "testfile", info)
  216. assert.NoError(t, err)
  217. assert.FileExists(t, testfile)
  218. os.RemoveAll(homeDir)
  219. Config.Actions = actionsCopy
  220. }
  221. func TestUnconfiguredHook(t *testing.T) {
  222. actionsCopy := Config.Actions
  223. Config.Actions = ProtocolActions{
  224. ExecuteOn: []string{operationDownload},
  225. Hook: "",
  226. }
  227. pluginsConfig := []plugin.Config{
  228. {
  229. Type: "notifier",
  230. },
  231. }
  232. err := plugin.Initialize(pluginsConfig, true)
  233. assert.Error(t, err)
  234. assert.True(t, plugin.Handler.HasNotifiers())
  235. c := NewBaseConnection("id", ProtocolSFTP, "", "", dataprovider.User{})
  236. err = ExecutePreAction(c, OperationPreDownload, "", "", 0, 0)
  237. assert.NoError(t, err)
  238. err = ExecutePreAction(c, operationPreDelete, "", "", 0, 0)
  239. assert.ErrorIs(t, err, errUnconfiguredAction)
  240. ExecuteActionNotification(c, operationDownload, "", "", "", "", "", 0, nil)
  241. err = plugin.Initialize(nil, true)
  242. assert.NoError(t, err)
  243. assert.False(t, plugin.Handler.HasNotifiers())
  244. Config.Actions = actionsCopy
  245. }
  246. type actionHandlerStub struct {
  247. called bool
  248. }
  249. func (h *actionHandlerStub) Handle(event *notifier.FsEvent) error {
  250. h.called = true
  251. return nil
  252. }
  253. func TestInitializeActionHandler(t *testing.T) {
  254. handler := &actionHandlerStub{}
  255. InitializeActionHandler(handler)
  256. t.Cleanup(func() {
  257. InitializeActionHandler(&defaultActionHandler{})
  258. })
  259. err := actionHandler.Handle(&notifier.FsEvent{})
  260. assert.NoError(t, err)
  261. assert.True(t, handler.called)
  262. }