dataretention_test.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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/exec"
  19. "runtime"
  20. "testing"
  21. "time"
  22. "github.com/sftpgo/sdk"
  23. "github.com/stretchr/testify/assert"
  24. "github.com/stretchr/testify/require"
  25. "github.com/drakkan/sftpgo/v2/internal/dataprovider"
  26. "github.com/drakkan/sftpgo/v2/internal/smtp"
  27. )
  28. func TestRetentionValidation(t *testing.T) {
  29. check := RetentionCheck{}
  30. check.Folders = []dataprovider.FolderRetention{
  31. {
  32. Path: "/",
  33. Retention: -1,
  34. },
  35. }
  36. err := check.Validate()
  37. require.Error(t, err)
  38. assert.Contains(t, err.Error(), "invalid folder retention")
  39. check.Folders = []dataprovider.FolderRetention{
  40. {
  41. Path: "/ab/..",
  42. Retention: 0,
  43. },
  44. }
  45. err = check.Validate()
  46. require.Error(t, err)
  47. assert.Contains(t, err.Error(), "nothing to delete")
  48. assert.Equal(t, "/", check.Folders[0].Path)
  49. check.Folders = append(check.Folders, dataprovider.FolderRetention{
  50. Path: "/../..",
  51. Retention: 24,
  52. })
  53. err = check.Validate()
  54. require.Error(t, err)
  55. assert.Contains(t, err.Error(), `duplicated folder path "/"`)
  56. check.Folders = []dataprovider.FolderRetention{
  57. {
  58. Path: "/dir1",
  59. Retention: 48,
  60. },
  61. {
  62. Path: "/dir2",
  63. Retention: 96,
  64. },
  65. }
  66. err = check.Validate()
  67. assert.NoError(t, err)
  68. assert.Len(t, check.Notifications, 0)
  69. assert.Empty(t, check.Email)
  70. check.Notifications = []RetentionCheckNotification{RetentionCheckNotificationEmail}
  71. err = check.Validate()
  72. require.Error(t, err)
  73. assert.Contains(t, err.Error(), "you must configure an SMTP server")
  74. smtpCfg := smtp.Config{
  75. Host: "mail.example.com",
  76. Port: 25,
  77. TemplatesPath: "templates",
  78. }
  79. err = smtpCfg.Initialize(configDir)
  80. require.NoError(t, err)
  81. err = check.Validate()
  82. require.Error(t, err)
  83. assert.Contains(t, err.Error(), "you must add a valid email address")
  84. check.Email = "[email protected]"
  85. err = check.Validate()
  86. assert.NoError(t, err)
  87. smtpCfg = smtp.Config{}
  88. err = smtpCfg.Initialize(configDir)
  89. require.NoError(t, err)
  90. check.Notifications = []RetentionCheckNotification{RetentionCheckNotificationHook}
  91. err = check.Validate()
  92. require.Error(t, err)
  93. assert.Contains(t, err.Error(), "data_retention_hook")
  94. check.Notifications = []string{"not valid"}
  95. err = check.Validate()
  96. require.Error(t, err)
  97. assert.Contains(t, err.Error(), "invalid notification")
  98. }
  99. func TestRetentionEmailNotifications(t *testing.T) {
  100. smtpCfg := smtp.Config{
  101. Host: "127.0.0.1",
  102. Port: 2525,
  103. TemplatesPath: "templates",
  104. }
  105. err := smtpCfg.Initialize(configDir)
  106. require.NoError(t, err)
  107. user := dataprovider.User{
  108. BaseUser: sdk.BaseUser{
  109. Username: "user1",
  110. },
  111. }
  112. user.Permissions = make(map[string][]string)
  113. user.Permissions["/"] = []string{dataprovider.PermAny}
  114. check := RetentionCheck{
  115. Notifications: []RetentionCheckNotification{RetentionCheckNotificationEmail},
  116. Email: "[email protected]",
  117. results: []*folderRetentionCheckResult{
  118. {
  119. Path: "/",
  120. Retention: 24,
  121. DeletedFiles: 10,
  122. DeletedSize: 32657,
  123. Elapsed: 10 * time.Second,
  124. },
  125. },
  126. }
  127. conn := NewBaseConnection("", "", "", "", user)
  128. conn.SetProtocol(ProtocolDataRetention)
  129. conn.ID = fmt.Sprintf("data_retention_%v", user.Username)
  130. check.conn = conn
  131. check.sendNotifications(1*time.Second, nil)
  132. err = check.sendEmailNotification(1*time.Second, nil)
  133. assert.NoError(t, err)
  134. err = check.sendEmailNotification(1*time.Second, errors.New("test error"))
  135. assert.NoError(t, err)
  136. smtpCfg.Port = 2626
  137. err = smtpCfg.Initialize(configDir)
  138. require.NoError(t, err)
  139. err = check.sendEmailNotification(1*time.Second, nil)
  140. assert.Error(t, err)
  141. smtpCfg = smtp.Config{}
  142. err = smtpCfg.Initialize(configDir)
  143. require.NoError(t, err)
  144. err = check.sendEmailNotification(1*time.Second, nil)
  145. assert.Error(t, err)
  146. }
  147. func TestRetentionHookNotifications(t *testing.T) {
  148. dataRetentionHook := Config.DataRetentionHook
  149. Config.DataRetentionHook = fmt.Sprintf("http://%v", httpAddr)
  150. user := dataprovider.User{
  151. BaseUser: sdk.BaseUser{
  152. Username: "user2",
  153. },
  154. }
  155. user.Permissions = make(map[string][]string)
  156. user.Permissions["/"] = []string{dataprovider.PermAny}
  157. check := RetentionCheck{
  158. Notifications: []RetentionCheckNotification{RetentionCheckNotificationHook},
  159. results: []*folderRetentionCheckResult{
  160. {
  161. Path: "/",
  162. Retention: 24,
  163. DeletedFiles: 10,
  164. DeletedSize: 32657,
  165. Elapsed: 10 * time.Second,
  166. },
  167. },
  168. }
  169. conn := NewBaseConnection("", "", "", "", user)
  170. conn.SetProtocol(ProtocolDataRetention)
  171. conn.ID = fmt.Sprintf("data_retention_%v", user.Username)
  172. check.conn = conn
  173. check.sendNotifications(1*time.Second, nil)
  174. err := check.sendHookNotification(1*time.Second, nil)
  175. assert.NoError(t, err)
  176. Config.DataRetentionHook = fmt.Sprintf("http://%v/404", httpAddr)
  177. err = check.sendHookNotification(1*time.Second, nil)
  178. assert.ErrorIs(t, err, errUnexpectedHTTResponse)
  179. Config.DataRetentionHook = "http://foo\x7f.com/retention"
  180. err = check.sendHookNotification(1*time.Second, err)
  181. assert.Error(t, err)
  182. Config.DataRetentionHook = "relativepath"
  183. err = check.sendHookNotification(1*time.Second, err)
  184. assert.Error(t, err)
  185. if runtime.GOOS != osWindows {
  186. hookCmd, err := exec.LookPath("true")
  187. assert.NoError(t, err)
  188. Config.DataRetentionHook = hookCmd
  189. err = check.sendHookNotification(1*time.Second, err)
  190. assert.NoError(t, err)
  191. }
  192. Config.DataRetentionHook = dataRetentionHook
  193. }
  194. func TestRetentionPermissionsAndGetFolder(t *testing.T) {
  195. user := dataprovider.User{
  196. BaseUser: sdk.BaseUser{
  197. Username: "user1",
  198. },
  199. }
  200. user.Permissions = make(map[string][]string)
  201. user.Permissions["/"] = []string{dataprovider.PermListItems, dataprovider.PermDelete}
  202. user.Permissions["/dir1"] = []string{dataprovider.PermListItems}
  203. user.Permissions["/dir2/sub1"] = []string{dataprovider.PermCreateDirs}
  204. user.Permissions["/dir2/sub2"] = []string{dataprovider.PermDelete}
  205. check := RetentionCheck{
  206. Folders: []dataprovider.FolderRetention{
  207. {
  208. Path: "/dir2",
  209. Retention: 24 * 7,
  210. IgnoreUserPermissions: true,
  211. },
  212. {
  213. Path: "/dir3",
  214. Retention: 24 * 7,
  215. IgnoreUserPermissions: false,
  216. },
  217. {
  218. Path: "/dir2/sub1/sub",
  219. Retention: 24,
  220. IgnoreUserPermissions: true,
  221. },
  222. },
  223. }
  224. conn := NewBaseConnection("", "", "", "", user)
  225. conn.SetProtocol(ProtocolDataRetention)
  226. conn.ID = fmt.Sprintf("data_retention_%v", user.Username)
  227. check.conn = conn
  228. check.updateUserPermissions()
  229. assert.Equal(t, []string{dataprovider.PermListItems, dataprovider.PermDelete}, conn.User.Permissions["/"])
  230. assert.Equal(t, []string{dataprovider.PermListItems}, conn.User.Permissions["/dir1"])
  231. assert.Equal(t, []string{dataprovider.PermAny}, conn.User.Permissions["/dir2"])
  232. assert.Equal(t, []string{dataprovider.PermAny}, conn.User.Permissions["/dir2/sub1/sub"])
  233. assert.Equal(t, []string{dataprovider.PermCreateDirs}, conn.User.Permissions["/dir2/sub1"])
  234. assert.Equal(t, []string{dataprovider.PermDelete}, conn.User.Permissions["/dir2/sub2"])
  235. _, err := check.getFolderRetention("/")
  236. assert.Error(t, err)
  237. folder, err := check.getFolderRetention("/dir3")
  238. assert.NoError(t, err)
  239. assert.Equal(t, "/dir3", folder.Path)
  240. folder, err = check.getFolderRetention("/dir2/sub3")
  241. assert.NoError(t, err)
  242. assert.Equal(t, "/dir2", folder.Path)
  243. folder, err = check.getFolderRetention("/dir2/sub2")
  244. assert.NoError(t, err)
  245. assert.Equal(t, "/dir2", folder.Path)
  246. folder, err = check.getFolderRetention("/dir2/sub1")
  247. assert.NoError(t, err)
  248. assert.Equal(t, "/dir2", folder.Path)
  249. folder, err = check.getFolderRetention("/dir2/sub1/sub/sub")
  250. assert.NoError(t, err)
  251. assert.Equal(t, "/dir2/sub1/sub", folder.Path)
  252. }
  253. func TestRetentionCheckAddRemove(t *testing.T) {
  254. username := "username"
  255. user := dataprovider.User{
  256. BaseUser: sdk.BaseUser{
  257. Username: username,
  258. },
  259. }
  260. user.Permissions = make(map[string][]string)
  261. user.Permissions["/"] = []string{dataprovider.PermAny}
  262. check := RetentionCheck{
  263. Folders: []dataprovider.FolderRetention{
  264. {
  265. Path: "/",
  266. Retention: 48,
  267. },
  268. },
  269. Notifications: []RetentionCheckNotification{RetentionCheckNotificationHook},
  270. }
  271. assert.NotNil(t, RetentionChecks.Add(check, &user))
  272. checks := RetentionChecks.Get()
  273. require.Len(t, checks, 1)
  274. assert.Equal(t, username, checks[0].Username)
  275. assert.Greater(t, checks[0].StartTime, int64(0))
  276. require.Len(t, checks[0].Folders, 1)
  277. assert.Equal(t, check.Folders[0].Path, checks[0].Folders[0].Path)
  278. assert.Equal(t, check.Folders[0].Retention, checks[0].Folders[0].Retention)
  279. require.Len(t, checks[0].Notifications, 1)
  280. assert.Equal(t, RetentionCheckNotificationHook, checks[0].Notifications[0])
  281. assert.Nil(t, RetentionChecks.Add(check, &user))
  282. assert.True(t, RetentionChecks.remove(username))
  283. require.Len(t, RetentionChecks.Get(), 0)
  284. assert.False(t, RetentionChecks.remove(username))
  285. }
  286. func TestCleanupErrors(t *testing.T) {
  287. user := dataprovider.User{
  288. BaseUser: sdk.BaseUser{
  289. Username: "u",
  290. },
  291. }
  292. user.Permissions = make(map[string][]string)
  293. user.Permissions["/"] = []string{dataprovider.PermAny}
  294. check := &RetentionCheck{
  295. Folders: []dataprovider.FolderRetention{
  296. {
  297. Path: "/path",
  298. Retention: 48,
  299. },
  300. },
  301. }
  302. check = RetentionChecks.Add(*check, &user)
  303. require.NotNil(t, check)
  304. err := check.removeFile("missing file", nil)
  305. assert.Error(t, err)
  306. err = check.cleanupFolder("/")
  307. assert.Error(t, err)
  308. assert.True(t, RetentionChecks.remove(user.Username))
  309. }