actions_test.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. // Copyright (C) 2019-2023 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")), 0)
  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), 0)
  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), 0)
  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)), 0)
  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), 0)
  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), 0)
  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), 0)
  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), 0)
  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, 0)
  126. status, err := actionHandler.Handle(a)
  127. assert.NoError(t, err)
  128. assert.Equal(t, 1, status)
  129. Config.Actions.Hook = "http://invalid:1234"
  130. status, err = actionHandler.Handle(a)
  131. assert.Error(t, err)
  132. assert.Equal(t, 1, status)
  133. Config.Actions.Hook = fmt.Sprintf("http://%v/404", httpAddr)
  134. status, err = actionHandler.Handle(a)
  135. if assert.Error(t, err) {
  136. assert.EqualError(t, err, errUnexpectedHTTResponse.Error())
  137. }
  138. assert.Equal(t, 1, status)
  139. Config.Actions = actionsCopy
  140. }
  141. func TestActionCMD(t *testing.T) {
  142. if runtime.GOOS == osWindows {
  143. t.Skip("this test is not available on Windows")
  144. }
  145. actionsCopy := Config.Actions
  146. hookCmd, err := exec.LookPath("true")
  147. assert.NoError(t, err)
  148. Config.Actions = ProtocolActions{
  149. ExecuteOn: []string{operationDownload},
  150. Hook: hookCmd,
  151. }
  152. user := &dataprovider.User{
  153. BaseUser: sdk.BaseUser{
  154. Username: "username",
  155. },
  156. }
  157. sessionID := shortuuid.New()
  158. a := newActionNotification(user, operationDownload, "path", "vpath", "target", "", "", ProtocolSFTP, "", sessionID,
  159. 123, 0, 1, 0)
  160. status, err := actionHandler.Handle(a)
  161. assert.NoError(t, err)
  162. assert.Equal(t, 1, status)
  163. c := NewBaseConnection("id", ProtocolSFTP, "", "", *user)
  164. err = ExecuteActionNotification(c, OperationSSHCmd, "path", "vpath", "target", "vtarget", "sha1sum", 0, nil, 0)
  165. assert.NoError(t, err)
  166. err = ExecuteActionNotification(c, operationDownload, "path", "vpath", "", "", "", 0, nil, 0)
  167. assert.NoError(t, err)
  168. Config.Actions = actionsCopy
  169. }
  170. func TestWrongActions(t *testing.T) {
  171. actionsCopy := Config.Actions
  172. badCommand := "/bad/command"
  173. if runtime.GOOS == osWindows {
  174. badCommand = "C:\\bad\\command"
  175. }
  176. Config.Actions = ProtocolActions{
  177. ExecuteOn: []string{operationUpload},
  178. Hook: badCommand,
  179. }
  180. user := &dataprovider.User{
  181. BaseUser: sdk.BaseUser{
  182. Username: "username",
  183. },
  184. }
  185. a := newActionNotification(user, operationUpload, "", "", "", "", "", ProtocolSFTP, "", xid.New().String(),
  186. 123, 0, 1, 0)
  187. status, err := actionHandler.Handle(a)
  188. assert.Error(t, err, "action with bad command must fail")
  189. assert.Equal(t, 1, status)
  190. a.Action = operationDelete
  191. status, err = actionHandler.Handle(a)
  192. assert.NoError(t, err)
  193. assert.Equal(t, 0, status)
  194. Config.Actions.Hook = "http://foo\x7f.com/"
  195. a.Action = operationUpload
  196. status, err = actionHandler.Handle(a)
  197. assert.Error(t, err, "action with bad url must fail")
  198. assert.Equal(t, 1, status)
  199. Config.Actions.Hook = ""
  200. status, err = actionHandler.Handle(a)
  201. assert.NoError(t, err)
  202. assert.Equal(t, 0, status)
  203. Config.Actions.Hook = "relative path"
  204. status, err = actionHandler.Handle(a)
  205. if assert.Error(t, err) {
  206. assert.EqualError(t, err, fmt.Sprintf("invalid notification command %q", Config.Actions.Hook))
  207. }
  208. assert.Equal(t, 1, status)
  209. Config.Actions = actionsCopy
  210. }
  211. func TestPreDeleteAction(t *testing.T) {
  212. if runtime.GOOS == osWindows {
  213. t.Skip("this test is not available on Windows")
  214. }
  215. actionsCopy := Config.Actions
  216. hookCmd, err := exec.LookPath("true")
  217. assert.NoError(t, err)
  218. Config.Actions = ProtocolActions{
  219. ExecuteOn: []string{operationPreDelete},
  220. Hook: "missing hook",
  221. }
  222. homeDir := filepath.Join(os.TempDir(), "test_user")
  223. err = os.MkdirAll(homeDir, os.ModePerm)
  224. assert.NoError(t, err)
  225. user := dataprovider.User{
  226. BaseUser: sdk.BaseUser{
  227. Username: "username",
  228. HomeDir: homeDir,
  229. },
  230. }
  231. user.Permissions = make(map[string][]string)
  232. user.Permissions["/"] = []string{dataprovider.PermAny}
  233. fs := vfs.NewOsFs("id", homeDir, "")
  234. c := NewBaseConnection("id", ProtocolSFTP, "", "", user)
  235. testfile := filepath.Join(user.HomeDir, "testfile")
  236. err = os.WriteFile(testfile, []byte("test"), os.ModePerm)
  237. assert.NoError(t, err)
  238. info, err := os.Stat(testfile)
  239. assert.NoError(t, err)
  240. err = c.RemoveFile(fs, testfile, "testfile", info)
  241. assert.ErrorIs(t, err, c.GetPermissionDeniedError())
  242. assert.FileExists(t, testfile)
  243. Config.Actions.Hook = hookCmd
  244. err = c.RemoveFile(fs, testfile, "testfile", info)
  245. assert.NoError(t, err)
  246. assert.NoFileExists(t, testfile)
  247. os.RemoveAll(homeDir)
  248. Config.Actions = actionsCopy
  249. }
  250. func TestUnconfiguredHook(t *testing.T) {
  251. actionsCopy := Config.Actions
  252. Config.Actions = ProtocolActions{
  253. ExecuteOn: []string{operationDownload},
  254. Hook: "",
  255. }
  256. pluginsConfig := []plugin.Config{
  257. {
  258. Type: "notifier",
  259. },
  260. }
  261. err := plugin.Initialize(pluginsConfig, "debug")
  262. assert.Error(t, err)
  263. assert.True(t, plugin.Handler.HasNotifiers())
  264. c := NewBaseConnection("id", ProtocolSFTP, "", "", dataprovider.User{})
  265. status, err := ExecutePreAction(c, OperationPreDownload, "", "", 0, 0)
  266. assert.NoError(t, err)
  267. assert.Equal(t, status, 0)
  268. status, err = ExecutePreAction(c, operationPreDelete, "", "", 0, 0)
  269. assert.NoError(t, err)
  270. assert.Equal(t, status, 0)
  271. err = ExecuteActionNotification(c, operationDownload, "", "", "", "", "", 0, nil, 0)
  272. assert.NoError(t, err)
  273. err = plugin.Initialize(nil, "debug")
  274. assert.NoError(t, err)
  275. assert.False(t, plugin.Handler.HasNotifiers())
  276. Config.Actions = actionsCopy
  277. }
  278. type actionHandlerStub struct {
  279. called bool
  280. }
  281. func (h *actionHandlerStub) Handle(_ *notifier.FsEvent) (int, error) {
  282. h.called = true
  283. return 1, nil
  284. }
  285. func TestInitializeActionHandler(t *testing.T) {
  286. handler := &actionHandlerStub{}
  287. InitializeActionHandler(handler)
  288. t.Cleanup(func() {
  289. InitializeActionHandler(&defaultActionHandler{})
  290. })
  291. status, err := actionHandler.Handle(&notifier.FsEvent{})
  292. assert.NoError(t, err)
  293. assert.True(t, handler.called)
  294. assert.Equal(t, 1, status)
  295. }