1
0

dataretention_test.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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(nil)
  133. assert.NoError(t, err)
  134. err = check.sendEmailNotification(errors.New("test error"))
  135. assert.NoError(t, err)
  136. check.results = nil
  137. err = check.sendEmailNotification(nil)
  138. if assert.Error(t, err) {
  139. assert.Contains(t, err.Error(), "no data retention report available")
  140. }
  141. smtpCfg.Port = 2626
  142. err = smtpCfg.Initialize(configDir)
  143. require.NoError(t, err)
  144. err = check.sendEmailNotification(nil)
  145. assert.Error(t, err)
  146. check.results = []folderRetentionCheckResult{
  147. {
  148. Path: "/",
  149. Retention: 24,
  150. DeletedFiles: 20,
  151. DeletedSize: 456789,
  152. Elapsed: 12 * time.Second,
  153. },
  154. }
  155. smtpCfg = smtp.Config{}
  156. err = smtpCfg.Initialize(configDir)
  157. require.NoError(t, err)
  158. err = check.sendEmailNotification(nil)
  159. assert.Error(t, err)
  160. }
  161. func TestRetentionHookNotifications(t *testing.T) {
  162. dataRetentionHook := Config.DataRetentionHook
  163. Config.DataRetentionHook = fmt.Sprintf("http://%v", httpAddr)
  164. user := dataprovider.User{
  165. BaseUser: sdk.BaseUser{
  166. Username: "user2",
  167. },
  168. }
  169. user.Permissions = make(map[string][]string)
  170. user.Permissions["/"] = []string{dataprovider.PermAny}
  171. check := RetentionCheck{
  172. Notifications: []RetentionCheckNotification{RetentionCheckNotificationHook},
  173. results: []folderRetentionCheckResult{
  174. {
  175. Path: "/",
  176. Retention: 24,
  177. DeletedFiles: 10,
  178. DeletedSize: 32657,
  179. Elapsed: 10 * time.Second,
  180. },
  181. },
  182. }
  183. conn := NewBaseConnection("", "", "", "", user)
  184. conn.SetProtocol(ProtocolDataRetention)
  185. conn.ID = fmt.Sprintf("data_retention_%v", user.Username)
  186. check.conn = conn
  187. check.sendNotifications(1*time.Second, nil)
  188. err := check.sendHookNotification(1*time.Second, nil)
  189. assert.NoError(t, err)
  190. Config.DataRetentionHook = fmt.Sprintf("http://%v/404", httpAddr)
  191. err = check.sendHookNotification(1*time.Second, nil)
  192. assert.ErrorIs(t, err, errUnexpectedHTTResponse)
  193. Config.DataRetentionHook = "http://foo\x7f.com/retention"
  194. err = check.sendHookNotification(1*time.Second, err)
  195. assert.Error(t, err)
  196. Config.DataRetentionHook = "relativepath"
  197. err = check.sendHookNotification(1*time.Second, err)
  198. assert.Error(t, err)
  199. if runtime.GOOS != osWindows {
  200. hookCmd, err := exec.LookPath("true")
  201. assert.NoError(t, err)
  202. Config.DataRetentionHook = hookCmd
  203. err = check.sendHookNotification(1*time.Second, err)
  204. assert.NoError(t, err)
  205. }
  206. Config.DataRetentionHook = dataRetentionHook
  207. }
  208. func TestRetentionPermissionsAndGetFolder(t *testing.T) {
  209. user := dataprovider.User{
  210. BaseUser: sdk.BaseUser{
  211. Username: "user1",
  212. },
  213. }
  214. user.Permissions = make(map[string][]string)
  215. user.Permissions["/"] = []string{dataprovider.PermListItems, dataprovider.PermDelete}
  216. user.Permissions["/dir1"] = []string{dataprovider.PermListItems}
  217. user.Permissions["/dir2/sub1"] = []string{dataprovider.PermCreateDirs}
  218. user.Permissions["/dir2/sub2"] = []string{dataprovider.PermDelete}
  219. check := RetentionCheck{
  220. Folders: []dataprovider.FolderRetention{
  221. {
  222. Path: "/dir2",
  223. Retention: 24 * 7,
  224. IgnoreUserPermissions: true,
  225. },
  226. {
  227. Path: "/dir3",
  228. Retention: 24 * 7,
  229. IgnoreUserPermissions: false,
  230. },
  231. {
  232. Path: "/dir2/sub1/sub",
  233. Retention: 24,
  234. IgnoreUserPermissions: true,
  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.PermListItems, dataprovider.PermDelete}, conn.User.Permissions["/"])
  244. assert.Equal(t, []string{dataprovider.PermListItems}, conn.User.Permissions["/dir1"])
  245. assert.Equal(t, []string{dataprovider.PermAny}, conn.User.Permissions["/dir2"])
  246. assert.Equal(t, []string{dataprovider.PermAny}, conn.User.Permissions["/dir2/sub1/sub"])
  247. assert.Equal(t, []string{dataprovider.PermCreateDirs}, conn.User.Permissions["/dir2/sub1"])
  248. assert.Equal(t, []string{dataprovider.PermDelete}, conn.User.Permissions["/dir2/sub2"])
  249. _, err := check.getFolderRetention("/")
  250. assert.Error(t, err)
  251. folder, err := check.getFolderRetention("/dir3")
  252. assert.NoError(t, err)
  253. assert.Equal(t, "/dir3", folder.Path)
  254. folder, err = check.getFolderRetention("/dir2/sub3")
  255. assert.NoError(t, err)
  256. assert.Equal(t, "/dir2", folder.Path)
  257. folder, err = check.getFolderRetention("/dir2/sub2")
  258. assert.NoError(t, err)
  259. assert.Equal(t, "/dir2", folder.Path)
  260. folder, err = check.getFolderRetention("/dir2/sub1")
  261. assert.NoError(t, err)
  262. assert.Equal(t, "/dir2", folder.Path)
  263. folder, err = check.getFolderRetention("/dir2/sub1/sub/sub")
  264. assert.NoError(t, err)
  265. assert.Equal(t, "/dir2/sub1/sub", folder.Path)
  266. }
  267. func TestRetentionCheckAddRemove(t *testing.T) {
  268. username := "username"
  269. user := dataprovider.User{
  270. BaseUser: sdk.BaseUser{
  271. Username: username,
  272. },
  273. }
  274. user.Permissions = make(map[string][]string)
  275. user.Permissions["/"] = []string{dataprovider.PermAny}
  276. check := RetentionCheck{
  277. Folders: []dataprovider.FolderRetention{
  278. {
  279. Path: "/",
  280. Retention: 48,
  281. },
  282. },
  283. Notifications: []RetentionCheckNotification{RetentionCheckNotificationHook},
  284. }
  285. assert.NotNil(t, RetentionChecks.Add(check, &user))
  286. checks := RetentionChecks.Get()
  287. require.Len(t, checks, 1)
  288. assert.Equal(t, username, checks[0].Username)
  289. assert.Greater(t, checks[0].StartTime, int64(0))
  290. require.Len(t, checks[0].Folders, 1)
  291. assert.Equal(t, check.Folders[0].Path, checks[0].Folders[0].Path)
  292. assert.Equal(t, check.Folders[0].Retention, checks[0].Folders[0].Retention)
  293. require.Len(t, checks[0].Notifications, 1)
  294. assert.Equal(t, RetentionCheckNotificationHook, checks[0].Notifications[0])
  295. assert.Nil(t, RetentionChecks.Add(check, &user))
  296. assert.True(t, RetentionChecks.remove(username))
  297. require.Len(t, RetentionChecks.Get(), 0)
  298. assert.False(t, RetentionChecks.remove(username))
  299. }
  300. func TestCleanupErrors(t *testing.T) {
  301. user := dataprovider.User{
  302. BaseUser: sdk.BaseUser{
  303. Username: "u",
  304. },
  305. }
  306. user.Permissions = make(map[string][]string)
  307. user.Permissions["/"] = []string{dataprovider.PermAny}
  308. check := &RetentionCheck{
  309. Folders: []dataprovider.FolderRetention{
  310. {
  311. Path: "/path",
  312. Retention: 48,
  313. },
  314. },
  315. }
  316. check = RetentionChecks.Add(*check, &user)
  317. require.NotNil(t, check)
  318. err := check.removeFile("missing file", nil)
  319. assert.Error(t, err)
  320. err = check.cleanupFolder("/")
  321. assert.Error(t, err)
  322. assert.True(t, RetentionChecks.remove(user.Username))
  323. }