actions_test.go 9.7 KB

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