dataretention_test.go 12 KB

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