actions_test.go 10 KB

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