dataretention_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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. },
  228. {
  229. Path: "/dir3",
  230. Retention: 24 * 7,
  231. },
  232. {
  233. Path: "/dir2/sub1/sub",
  234. Retention: 24,
  235. },
  236. },
  237. }
  238. conn := NewBaseConnection("", "", "", "", user)
  239. conn.SetProtocol(ProtocolDataRetention)
  240. conn.ID = fmt.Sprintf("data_retention_%v", user.Username)
  241. check.conn = conn
  242. check.updateUserPermissions()
  243. assert.Equal(t, []string{dataprovider.PermAny}, conn.User.Permissions["/"])
  244. assert.Equal(t, []string{dataprovider.PermAny}, conn.User.Permissions["/dir1"])
  245. assert.Equal(t, []string{dataprovider.PermAny}, conn.User.Permissions["/dir2/sub1"])
  246. assert.Equal(t, []string{dataprovider.PermAny}, conn.User.Permissions["/dir2/sub2"])
  247. _, err := check.getFolderRetention("/")
  248. assert.Error(t, err)
  249. folder, err := check.getFolderRetention("/dir3")
  250. assert.NoError(t, err)
  251. assert.Equal(t, "/dir3", folder.Path)
  252. folder, err = check.getFolderRetention("/dir2/sub3")
  253. assert.NoError(t, err)
  254. assert.Equal(t, "/dir2", folder.Path)
  255. folder, err = check.getFolderRetention("/dir2/sub2")
  256. assert.NoError(t, err)
  257. assert.Equal(t, "/dir2", folder.Path)
  258. folder, err = check.getFolderRetention("/dir2/sub1")
  259. assert.NoError(t, err)
  260. assert.Equal(t, "/dir2", folder.Path)
  261. folder, err = check.getFolderRetention("/dir2/sub1/sub/sub")
  262. assert.NoError(t, err)
  263. assert.Equal(t, "/dir2/sub1/sub", folder.Path)
  264. }
  265. func TestRetentionCheckAddRemove(t *testing.T) {
  266. username := "username"
  267. user := dataprovider.User{
  268. BaseUser: sdk.BaseUser{
  269. Username: username,
  270. },
  271. }
  272. user.Permissions = make(map[string][]string)
  273. user.Permissions["/"] = []string{dataprovider.PermAny}
  274. check := RetentionCheck{
  275. Folders: []dataprovider.FolderRetention{
  276. {
  277. Path: "/",
  278. Retention: 48,
  279. },
  280. },
  281. Notifications: []RetentionCheckNotification{RetentionCheckNotificationHook},
  282. }
  283. assert.NotNil(t, RetentionChecks.Add(check, &user))
  284. checks := RetentionChecks.Get("")
  285. require.Len(t, checks, 1)
  286. assert.Equal(t, username, checks[0].Username)
  287. assert.Greater(t, checks[0].StartTime, int64(0))
  288. require.Len(t, checks[0].Folders, 1)
  289. assert.Equal(t, check.Folders[0].Path, checks[0].Folders[0].Path)
  290. assert.Equal(t, check.Folders[0].Retention, checks[0].Folders[0].Retention)
  291. require.Len(t, checks[0].Notifications, 1)
  292. assert.Equal(t, RetentionCheckNotificationHook, checks[0].Notifications[0])
  293. assert.Nil(t, RetentionChecks.Add(check, &user))
  294. assert.True(t, RetentionChecks.remove(username))
  295. require.Len(t, RetentionChecks.Get(""), 0)
  296. assert.False(t, RetentionChecks.remove(username))
  297. }
  298. func TestRetentionCheckRole(t *testing.T) {
  299. username := "retuser"
  300. role1 := "retrole1"
  301. role2 := "retrole2"
  302. user := dataprovider.User{
  303. BaseUser: sdk.BaseUser{
  304. Username: username,
  305. Role: role1,
  306. },
  307. }
  308. user.Permissions = make(map[string][]string)
  309. user.Permissions["/"] = []string{dataprovider.PermAny}
  310. check := RetentionCheck{
  311. Folders: []dataprovider.FolderRetention{
  312. {
  313. Path: "/",
  314. Retention: 48,
  315. },
  316. },
  317. Notifications: []RetentionCheckNotification{RetentionCheckNotificationHook},
  318. }
  319. assert.NotNil(t, RetentionChecks.Add(check, &user))
  320. checks := RetentionChecks.Get("")
  321. require.Len(t, checks, 1)
  322. assert.Empty(t, checks[0].Role)
  323. checks = RetentionChecks.Get(role1)
  324. require.Len(t, checks, 1)
  325. checks = RetentionChecks.Get(role2)
  326. require.Len(t, checks, 0)
  327. user.Role = ""
  328. assert.Nil(t, RetentionChecks.Add(check, &user))
  329. assert.True(t, RetentionChecks.remove(username))
  330. require.Len(t, RetentionChecks.Get(""), 0)
  331. }
  332. func TestCleanupErrors(t *testing.T) {
  333. user := dataprovider.User{
  334. BaseUser: sdk.BaseUser{
  335. Username: "u",
  336. },
  337. }
  338. user.Permissions = make(map[string][]string)
  339. user.Permissions["/"] = []string{dataprovider.PermAny}
  340. check := &RetentionCheck{
  341. Folders: []dataprovider.FolderRetention{
  342. {
  343. Path: "/path",
  344. Retention: 48,
  345. },
  346. },
  347. }
  348. check = RetentionChecks.Add(*check, &user)
  349. require.NotNil(t, check)
  350. err := check.removeFile("missing file", nil)
  351. assert.Error(t, err)
  352. err = check.cleanupFolder("/", 0)
  353. assert.Error(t, err)
  354. err = check.cleanupFolder("/", 1000)
  355. assert.ErrorIs(t, err, util.ErrRecursionTooDeep)
  356. assert.True(t, RetentionChecks.remove(user.Username))
  357. }