manager_test.go 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  1. package user
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "github.com/stretchr/testify/require"
  6. "github.com/stripe/stripe-go/v74"
  7. "golang.org/x/crypto/bcrypt"
  8. "heckel.io/ntfy/util"
  9. "net/netip"
  10. "path/filepath"
  11. "strings"
  12. "testing"
  13. "time"
  14. )
  15. const minBcryptTimingMillis = int64(50) // Ideally should be >100ms, but this should also run on a Raspberry Pi without massive resources
  16. func TestManager_FullScenario_Default_DenyAll(t *testing.T) {
  17. a := newTestManagerFromFile(t, filepath.Join(t.TempDir(), "user.db"), "", PermissionDenyAll, DefaultUserPasswordBcryptCost, DefaultUserStatsQueueWriterInterval)
  18. require.Nil(t, a.AddUser("phil", "phil", RoleAdmin))
  19. require.Nil(t, a.AddUser("ben", "ben", RoleUser))
  20. require.Nil(t, a.AllowAccess("ben", "mytopic", PermissionReadWrite))
  21. require.Nil(t, a.AllowAccess("ben", "readme", PermissionRead))
  22. require.Nil(t, a.AllowAccess("ben", "writeme", PermissionWrite))
  23. require.Nil(t, a.AllowAccess("ben", "everyonewrite", PermissionDenyAll)) // How unfair!
  24. require.Nil(t, a.AllowAccess(Everyone, "announcements", PermissionRead))
  25. require.Nil(t, a.AllowAccess(Everyone, "everyonewrite", PermissionReadWrite))
  26. require.Nil(t, a.AllowAccess(Everyone, "up*", PermissionWrite)) // Everyone can write to /up*
  27. phil, err := a.Authenticate("phil", "phil")
  28. require.Nil(t, err)
  29. require.Equal(t, "phil", phil.Name)
  30. require.True(t, strings.HasPrefix(phil.Hash, "$2a$10$"))
  31. require.Equal(t, RoleAdmin, phil.Role)
  32. philGrants, err := a.Grants("phil")
  33. require.Nil(t, err)
  34. require.Equal(t, []Grant{}, philGrants)
  35. ben, err := a.Authenticate("ben", "ben")
  36. require.Nil(t, err)
  37. require.Equal(t, "ben", ben.Name)
  38. require.True(t, strings.HasPrefix(ben.Hash, "$2a$10$"))
  39. require.Equal(t, RoleUser, ben.Role)
  40. benGrants, err := a.Grants("ben")
  41. require.Nil(t, err)
  42. require.Equal(t, []Grant{
  43. {"mytopic", PermissionReadWrite},
  44. {"writeme", PermissionWrite},
  45. {"readme", PermissionRead},
  46. {"everyonewrite", PermissionDenyAll},
  47. }, benGrants)
  48. notben, err := a.Authenticate("ben", "this is wrong")
  49. require.Nil(t, notben)
  50. require.Equal(t, ErrUnauthenticated, err)
  51. // Admin can do everything
  52. require.Nil(t, a.Authorize(phil, "sometopic", PermissionWrite))
  53. require.Nil(t, a.Authorize(phil, "mytopic", PermissionRead))
  54. require.Nil(t, a.Authorize(phil, "readme", PermissionWrite))
  55. require.Nil(t, a.Authorize(phil, "writeme", PermissionWrite))
  56. require.Nil(t, a.Authorize(phil, "announcements", PermissionWrite))
  57. require.Nil(t, a.Authorize(phil, "everyonewrite", PermissionWrite))
  58. // User cannot do everything
  59. require.Nil(t, a.Authorize(ben, "mytopic", PermissionWrite))
  60. require.Nil(t, a.Authorize(ben, "mytopic", PermissionRead))
  61. require.Nil(t, a.Authorize(ben, "readme", PermissionRead))
  62. require.Equal(t, ErrUnauthorized, a.Authorize(ben, "readme", PermissionWrite))
  63. require.Equal(t, ErrUnauthorized, a.Authorize(ben, "writeme", PermissionRead))
  64. require.Nil(t, a.Authorize(ben, "writeme", PermissionWrite))
  65. require.Nil(t, a.Authorize(ben, "writeme", PermissionWrite))
  66. require.Equal(t, ErrUnauthorized, a.Authorize(ben, "everyonewrite", PermissionRead))
  67. require.Equal(t, ErrUnauthorized, a.Authorize(ben, "everyonewrite", PermissionWrite))
  68. require.Nil(t, a.Authorize(ben, "announcements", PermissionRead))
  69. require.Equal(t, ErrUnauthorized, a.Authorize(ben, "announcements", PermissionWrite))
  70. // Everyone else can do barely anything
  71. require.Equal(t, ErrUnauthorized, a.Authorize(nil, "sometopicnotinthelist", PermissionRead))
  72. require.Equal(t, ErrUnauthorized, a.Authorize(nil, "sometopicnotinthelist", PermissionWrite))
  73. require.Equal(t, ErrUnauthorized, a.Authorize(nil, "mytopic", PermissionRead))
  74. require.Equal(t, ErrUnauthorized, a.Authorize(nil, "mytopic", PermissionWrite))
  75. require.Equal(t, ErrUnauthorized, a.Authorize(nil, "readme", PermissionRead))
  76. require.Equal(t, ErrUnauthorized, a.Authorize(nil, "readme", PermissionWrite))
  77. require.Equal(t, ErrUnauthorized, a.Authorize(nil, "writeme", PermissionRead))
  78. require.Equal(t, ErrUnauthorized, a.Authorize(nil, "writeme", PermissionWrite))
  79. require.Equal(t, ErrUnauthorized, a.Authorize(nil, "announcements", PermissionWrite))
  80. require.Nil(t, a.Authorize(nil, "announcements", PermissionRead))
  81. require.Nil(t, a.Authorize(nil, "everyonewrite", PermissionRead))
  82. require.Nil(t, a.Authorize(nil, "everyonewrite", PermissionWrite))
  83. require.Nil(t, a.Authorize(nil, "up1234", PermissionWrite)) // Wildcard permission
  84. require.Nil(t, a.Authorize(nil, "up5678", PermissionWrite))
  85. }
  86. func TestManager_AddUser_Invalid(t *testing.T) {
  87. a := newTestManager(t, PermissionDenyAll)
  88. require.Equal(t, ErrInvalidArgument, a.AddUser(" invalid ", "pass", RoleAdmin))
  89. require.Equal(t, ErrInvalidArgument, a.AddUser("validuser", "pass", "invalid-role"))
  90. }
  91. func TestManager_AddUser_Timing(t *testing.T) {
  92. a := newTestManagerFromFile(t, filepath.Join(t.TempDir(), "user.db"), "", PermissionDenyAll, DefaultUserPasswordBcryptCost, DefaultUserStatsQueueWriterInterval)
  93. start := time.Now().UnixMilli()
  94. require.Nil(t, a.AddUser("user", "pass", RoleAdmin))
  95. require.GreaterOrEqual(t, time.Now().UnixMilli()-start, minBcryptTimingMillis)
  96. }
  97. func TestManager_AddUser_And_Query(t *testing.T) {
  98. a := newTestManagerFromFile(t, filepath.Join(t.TempDir(), "user.db"), "", PermissionDenyAll, DefaultUserPasswordBcryptCost, DefaultUserStatsQueueWriterInterval)
  99. require.Nil(t, a.AddUser("user", "pass", RoleAdmin))
  100. require.Nil(t, a.ChangeBilling("user", &Billing{
  101. StripeCustomerID: "acct_123",
  102. StripeSubscriptionID: "sub_123",
  103. StripeSubscriptionStatus: stripe.SubscriptionStatusActive,
  104. StripeSubscriptionInterval: stripe.PriceRecurringIntervalMonth,
  105. StripeSubscriptionPaidUntil: time.Now().Add(time.Hour),
  106. StripeSubscriptionCancelAt: time.Unix(0, 0),
  107. }))
  108. u, err := a.User("user")
  109. require.Nil(t, err)
  110. require.Equal(t, "user", u.Name)
  111. u2, err := a.UserByID(u.ID)
  112. require.Nil(t, err)
  113. require.Equal(t, u.Name, u2.Name)
  114. u3, err := a.UserByStripeCustomer("acct_123")
  115. require.Nil(t, err)
  116. require.Equal(t, u.ID, u3.ID)
  117. }
  118. func TestManager_MarkUserRemoved_RemoveDeletedUsers(t *testing.T) {
  119. a := newTestManager(t, PermissionDenyAll)
  120. // Create user, add reservations and token
  121. require.Nil(t, a.AddUser("user", "pass", RoleAdmin))
  122. require.Nil(t, a.AddReservation("user", "mytopic", PermissionRead))
  123. u, err := a.User("user")
  124. require.Nil(t, err)
  125. require.False(t, u.Deleted)
  126. token, err := a.CreateToken(u.ID, "", time.Now().Add(time.Hour), netip.IPv4Unspecified())
  127. require.Nil(t, err)
  128. u, err = a.Authenticate("user", "pass")
  129. require.Nil(t, err)
  130. _, err = a.AuthenticateToken(token.Value)
  131. require.Nil(t, err)
  132. reservations, err := a.Reservations("user")
  133. require.Nil(t, err)
  134. require.Equal(t, 1, len(reservations))
  135. // Mark deleted: cannot auth anymore, and all reservations are gone
  136. require.Nil(t, a.MarkUserRemoved(u))
  137. _, err = a.Authenticate("user", "pass")
  138. require.Equal(t, ErrUnauthenticated, err)
  139. _, err = a.AuthenticateToken(token.Value)
  140. require.Equal(t, ErrUnauthenticated, err)
  141. reservations, err = a.Reservations("user")
  142. require.Nil(t, err)
  143. require.Equal(t, 0, len(reservations))
  144. // Make sure user is still there
  145. u, err = a.User("user")
  146. require.Nil(t, err)
  147. require.True(t, u.Deleted)
  148. _, err = a.db.Exec("UPDATE user SET deleted = ? WHERE id = ?", time.Now().Add(-1*(userHardDeleteAfterDuration+time.Hour)).Unix(), u.ID)
  149. require.Nil(t, err)
  150. require.Nil(t, a.RemoveDeletedUsers())
  151. _, err = a.User("user")
  152. require.Equal(t, ErrUserNotFound, err)
  153. }
  154. func TestManager_UserManagement(t *testing.T) {
  155. a := newTestManager(t, PermissionDenyAll)
  156. require.Nil(t, a.AddUser("phil", "phil", RoleAdmin))
  157. require.Nil(t, a.AddUser("ben", "ben", RoleUser))
  158. require.Nil(t, a.AllowAccess("ben", "mytopic", PermissionReadWrite))
  159. require.Nil(t, a.AllowAccess("ben", "readme", PermissionRead))
  160. require.Nil(t, a.AllowAccess("ben", "writeme", PermissionWrite))
  161. require.Nil(t, a.AllowAccess("ben", "everyonewrite", PermissionDenyAll)) // How unfair!
  162. require.Nil(t, a.AllowAccess(Everyone, "announcements", PermissionRead))
  163. require.Nil(t, a.AllowAccess(Everyone, "everyonewrite", PermissionReadWrite))
  164. // Query user details
  165. phil, err := a.User("phil")
  166. require.Nil(t, err)
  167. require.Equal(t, "phil", phil.Name)
  168. require.True(t, strings.HasPrefix(phil.Hash, "$2a$04$")) // Min cost for testing
  169. require.Equal(t, RoleAdmin, phil.Role)
  170. philGrants, err := a.Grants("phil")
  171. require.Nil(t, err)
  172. require.Equal(t, []Grant{}, philGrants)
  173. ben, err := a.User("ben")
  174. require.Nil(t, err)
  175. require.Equal(t, "ben", ben.Name)
  176. require.True(t, strings.HasPrefix(ben.Hash, "$2a$04$")) // Min cost for testing
  177. require.Equal(t, RoleUser, ben.Role)
  178. benGrants, err := a.Grants("ben")
  179. require.Nil(t, err)
  180. require.Equal(t, []Grant{
  181. {"mytopic", PermissionReadWrite},
  182. {"writeme", PermissionWrite},
  183. {"readme", PermissionRead},
  184. {"everyonewrite", PermissionDenyAll},
  185. }, benGrants)
  186. everyone, err := a.User(Everyone)
  187. require.Nil(t, err)
  188. require.Equal(t, "*", everyone.Name)
  189. require.Equal(t, "", everyone.Hash)
  190. require.Equal(t, RoleAnonymous, everyone.Role)
  191. everyoneGrants, err := a.Grants(Everyone)
  192. require.Nil(t, err)
  193. require.Equal(t, []Grant{
  194. {"everyonewrite", PermissionReadWrite},
  195. {"announcements", PermissionRead},
  196. }, everyoneGrants)
  197. // Ben: Before revoking
  198. require.Nil(t, a.AllowAccess("ben", "mytopic", PermissionReadWrite)) // Overwrite!
  199. require.Nil(t, a.AllowAccess("ben", "readme", PermissionRead))
  200. require.Nil(t, a.AllowAccess("ben", "writeme", PermissionWrite))
  201. require.Nil(t, a.Authorize(ben, "mytopic", PermissionRead))
  202. require.Nil(t, a.Authorize(ben, "mytopic", PermissionWrite))
  203. require.Nil(t, a.Authorize(ben, "readme", PermissionRead))
  204. require.Nil(t, a.Authorize(ben, "writeme", PermissionWrite))
  205. // Revoke access for "ben" to "mytopic", then check again
  206. require.Nil(t, a.ResetAccess("ben", "mytopic"))
  207. require.Equal(t, ErrUnauthorized, a.Authorize(ben, "mytopic", PermissionWrite)) // Revoked
  208. require.Equal(t, ErrUnauthorized, a.Authorize(ben, "mytopic", PermissionRead)) // Revoked
  209. require.Nil(t, a.Authorize(ben, "readme", PermissionRead)) // Unchanged
  210. require.Nil(t, a.Authorize(ben, "writeme", PermissionWrite)) // Unchanged
  211. // Revoke rest of the access
  212. require.Nil(t, a.ResetAccess("ben", ""))
  213. require.Equal(t, ErrUnauthorized, a.Authorize(ben, "readme", PermissionRead)) // Revoked
  214. require.Equal(t, ErrUnauthorized, a.Authorize(ben, "wrtiteme", PermissionWrite)) // Revoked
  215. // User list
  216. users, err := a.Users()
  217. require.Nil(t, err)
  218. require.Equal(t, 3, len(users))
  219. require.Equal(t, "phil", users[0].Name)
  220. require.Equal(t, "ben", users[1].Name)
  221. require.Equal(t, "*", users[2].Name)
  222. // Remove user
  223. require.Nil(t, a.RemoveUser("ben"))
  224. _, err = a.User("ben")
  225. require.Equal(t, ErrUserNotFound, err)
  226. users, err = a.Users()
  227. require.Nil(t, err)
  228. require.Equal(t, 2, len(users))
  229. require.Equal(t, "phil", users[0].Name)
  230. require.Equal(t, "*", users[1].Name)
  231. }
  232. func TestManager_ChangePassword(t *testing.T) {
  233. a := newTestManager(t, PermissionDenyAll)
  234. require.Nil(t, a.AddUser("phil", "phil", RoleAdmin))
  235. _, err := a.Authenticate("phil", "phil")
  236. require.Nil(t, err)
  237. require.Nil(t, a.ChangePassword("phil", "newpass"))
  238. _, err = a.Authenticate("phil", "phil")
  239. require.Equal(t, ErrUnauthenticated, err)
  240. _, err = a.Authenticate("phil", "newpass")
  241. require.Nil(t, err)
  242. }
  243. func TestManager_ChangeRole(t *testing.T) {
  244. a := newTestManager(t, PermissionDenyAll)
  245. require.Nil(t, a.AddUser("ben", "ben", RoleUser))
  246. require.Nil(t, a.AllowAccess("ben", "mytopic", PermissionReadWrite))
  247. require.Nil(t, a.AllowAccess("ben", "readme", PermissionRead))
  248. ben, err := a.User("ben")
  249. require.Nil(t, err)
  250. require.Equal(t, RoleUser, ben.Role)
  251. benGrants, err := a.Grants("ben")
  252. require.Nil(t, err)
  253. require.Equal(t, 2, len(benGrants))
  254. require.Nil(t, a.ChangeRole("ben", RoleAdmin))
  255. ben, err = a.User("ben")
  256. require.Nil(t, err)
  257. require.Equal(t, RoleAdmin, ben.Role)
  258. benGrants, err = a.Grants("ben")
  259. require.Nil(t, err)
  260. require.Equal(t, 0, len(benGrants))
  261. }
  262. func TestManager_Reservations(t *testing.T) {
  263. a := newTestManager(t, PermissionDenyAll)
  264. require.Nil(t, a.AddUser("phil", "phil", RoleUser))
  265. require.Nil(t, a.AddUser("ben", "ben", RoleUser))
  266. require.Nil(t, a.AddReservation("ben", "ztopic", PermissionDenyAll))
  267. require.Nil(t, a.AddReservation("ben", "readme", PermissionRead))
  268. require.Nil(t, a.AllowAccess("ben", "something-else", PermissionRead))
  269. reservations, err := a.Reservations("ben")
  270. require.Nil(t, err)
  271. require.Equal(t, 2, len(reservations))
  272. require.Equal(t, Reservation{
  273. Topic: "readme",
  274. Owner: PermissionReadWrite,
  275. Everyone: PermissionRead,
  276. }, reservations[0])
  277. require.Equal(t, Reservation{
  278. Topic: "ztopic",
  279. Owner: PermissionReadWrite,
  280. Everyone: PermissionDenyAll,
  281. }, reservations[1])
  282. b, err := a.HasReservation("ben", "readme")
  283. require.Nil(t, err)
  284. require.True(t, b)
  285. b, err = a.HasReservation("notben", "readme")
  286. require.Nil(t, err)
  287. require.False(t, b)
  288. b, err = a.HasReservation("ben", "something-else")
  289. require.Nil(t, err)
  290. require.False(t, b)
  291. count, err := a.ReservationsCount("ben")
  292. require.Nil(t, err)
  293. require.Equal(t, int64(2), count)
  294. count, err = a.ReservationsCount("phil")
  295. require.Nil(t, err)
  296. require.Equal(t, int64(0), count)
  297. err = a.AllowReservation("phil", "readme")
  298. require.Equal(t, errTopicOwnedByOthers, err)
  299. err = a.AllowReservation("phil", "not-reserved")
  300. require.Nil(t, err)
  301. // Now remove them again
  302. require.Nil(t, a.RemoveReservations("ben", "ztopic", "readme"))
  303. count, err = a.ReservationsCount("ben")
  304. require.Nil(t, err)
  305. require.Equal(t, int64(0), count)
  306. }
  307. func TestManager_ChangeRoleFromTierUserToAdmin(t *testing.T) {
  308. a := newTestManager(t, PermissionDenyAll)
  309. require.Nil(t, a.AddTier(&Tier{
  310. Code: "pro",
  311. Name: "ntfy Pro",
  312. StripeMonthlyPriceID: "price123",
  313. MessageLimit: 5_000,
  314. MessageExpiryDuration: 3 * 24 * time.Hour,
  315. EmailLimit: 50,
  316. ReservationLimit: 5,
  317. AttachmentFileSizeLimit: 52428800,
  318. AttachmentTotalSizeLimit: 524288000,
  319. AttachmentExpiryDuration: 24 * time.Hour,
  320. }))
  321. require.Nil(t, a.AddUser("ben", "ben", RoleUser))
  322. require.Nil(t, a.ChangeTier("ben", "pro"))
  323. require.Nil(t, a.AddReservation("ben", "mytopic", PermissionDenyAll))
  324. ben, err := a.User("ben")
  325. require.Nil(t, err)
  326. require.Equal(t, RoleUser, ben.Role)
  327. require.Equal(t, "pro", ben.Tier.Code)
  328. require.Equal(t, int64(5000), ben.Tier.MessageLimit)
  329. require.Equal(t, 3*24*time.Hour, ben.Tier.MessageExpiryDuration)
  330. require.Equal(t, int64(50), ben.Tier.EmailLimit)
  331. require.Equal(t, int64(5), ben.Tier.ReservationLimit)
  332. require.Equal(t, int64(52428800), ben.Tier.AttachmentFileSizeLimit)
  333. require.Equal(t, int64(524288000), ben.Tier.AttachmentTotalSizeLimit)
  334. require.Equal(t, 24*time.Hour, ben.Tier.AttachmentExpiryDuration)
  335. benGrants, err := a.Grants("ben")
  336. require.Nil(t, err)
  337. require.Equal(t, 1, len(benGrants))
  338. require.Equal(t, PermissionReadWrite, benGrants[0].Allow)
  339. everyoneGrants, err := a.Grants(Everyone)
  340. require.Nil(t, err)
  341. require.Equal(t, 1, len(everyoneGrants))
  342. require.Equal(t, PermissionDenyAll, everyoneGrants[0].Allow)
  343. benReservations, err := a.Reservations("ben")
  344. require.Nil(t, err)
  345. require.Equal(t, 1, len(benReservations))
  346. require.Equal(t, "mytopic", benReservations[0].Topic)
  347. require.Equal(t, PermissionReadWrite, benReservations[0].Owner)
  348. require.Equal(t, PermissionDenyAll, benReservations[0].Everyone)
  349. // Switch to admin, this should remove all grants and owned ACL entries
  350. require.Nil(t, a.ChangeRole("ben", RoleAdmin))
  351. benGrants, err = a.Grants("ben")
  352. require.Nil(t, err)
  353. require.Equal(t, 0, len(benGrants))
  354. everyoneGrants, err = a.Grants(Everyone)
  355. require.Nil(t, err)
  356. require.Equal(t, 0, len(everyoneGrants))
  357. }
  358. func TestManager_Token_Valid(t *testing.T) {
  359. a := newTestManager(t, PermissionDenyAll)
  360. require.Nil(t, a.AddUser("ben", "ben", RoleUser))
  361. u, err := a.User("ben")
  362. require.Nil(t, err)
  363. // Create token for user
  364. token, err := a.CreateToken(u.ID, "some label", time.Now().Add(72*time.Hour), netip.IPv4Unspecified())
  365. require.Nil(t, err)
  366. require.NotEmpty(t, token.Value)
  367. require.Equal(t, "some label", token.Label)
  368. require.True(t, time.Now().Add(71*time.Hour).Unix() < token.Expires.Unix())
  369. u2, err := a.AuthenticateToken(token.Value)
  370. require.Nil(t, err)
  371. require.Equal(t, u.Name, u2.Name)
  372. require.Equal(t, token.Value, u2.Token)
  373. token2, err := a.Token(u.ID, token.Value)
  374. require.Nil(t, err)
  375. require.Equal(t, token.Value, token2.Value)
  376. require.Equal(t, "some label", token2.Label)
  377. tokens, err := a.Tokens(u.ID)
  378. require.Nil(t, err)
  379. require.Equal(t, 1, len(tokens))
  380. require.Equal(t, "some label", tokens[0].Label)
  381. tokens, err = a.Tokens("u_notauser")
  382. require.Nil(t, err)
  383. require.Equal(t, 0, len(tokens))
  384. // Remove token and auth again
  385. require.Nil(t, a.RemoveToken(u2.ID, u2.Token))
  386. u3, err := a.AuthenticateToken(token.Value)
  387. require.Equal(t, ErrUnauthenticated, err)
  388. require.Nil(t, u3)
  389. tokens, err = a.Tokens(u.ID)
  390. require.Nil(t, err)
  391. require.Equal(t, 0, len(tokens))
  392. }
  393. func TestManager_Token_Invalid(t *testing.T) {
  394. a := newTestManager(t, PermissionDenyAll)
  395. require.Nil(t, a.AddUser("ben", "ben", RoleUser))
  396. u, err := a.AuthenticateToken(strings.Repeat("x", 32)) // 32 == token length
  397. require.Nil(t, u)
  398. require.Equal(t, ErrUnauthenticated, err)
  399. u, err = a.AuthenticateToken("not long enough anyway")
  400. require.Nil(t, u)
  401. require.Equal(t, ErrUnauthenticated, err)
  402. }
  403. func TestManager_Token_NotFound(t *testing.T) {
  404. a := newTestManager(t, PermissionDenyAll)
  405. _, err := a.Token("u_bla", "notfound")
  406. require.Equal(t, ErrTokenNotFound, err)
  407. }
  408. func TestManager_Token_Expire(t *testing.T) {
  409. a := newTestManager(t, PermissionDenyAll)
  410. require.Nil(t, a.AddUser("ben", "ben", RoleUser))
  411. u, err := a.User("ben")
  412. require.Nil(t, err)
  413. // Create tokens for user
  414. token1, err := a.CreateToken(u.ID, "", time.Now().Add(72*time.Hour), netip.IPv4Unspecified())
  415. require.Nil(t, err)
  416. require.NotEmpty(t, token1.Value)
  417. require.True(t, time.Now().Add(71*time.Hour).Unix() < token1.Expires.Unix())
  418. token2, err := a.CreateToken(u.ID, "", time.Now().Add(72*time.Hour), netip.IPv4Unspecified())
  419. require.Nil(t, err)
  420. require.NotEmpty(t, token2.Value)
  421. require.NotEqual(t, token1.Value, token2.Value)
  422. require.True(t, time.Now().Add(71*time.Hour).Unix() < token2.Expires.Unix())
  423. // See that tokens work
  424. _, err = a.AuthenticateToken(token1.Value)
  425. require.Nil(t, err)
  426. _, err = a.AuthenticateToken(token2.Value)
  427. require.Nil(t, err)
  428. // Modify token expiration in database
  429. _, err = a.db.Exec("UPDATE user_token SET expires = 1 WHERE token = ?", token1.Value)
  430. require.Nil(t, err)
  431. // Now token1 shouldn't work anymore
  432. _, err = a.AuthenticateToken(token1.Value)
  433. require.Equal(t, ErrUnauthenticated, err)
  434. result, err := a.db.Query("SELECT * from user_token WHERE token = ?", token1.Value)
  435. require.Nil(t, err)
  436. require.True(t, result.Next()) // Still a matching row
  437. require.Nil(t, result.Close())
  438. // Expire tokens and check database rows
  439. require.Nil(t, a.RemoveExpiredTokens())
  440. result, err = a.db.Query("SELECT * from user_token WHERE token = ?", token1.Value)
  441. require.Nil(t, err)
  442. require.False(t, result.Next()) // No matching row!
  443. require.Nil(t, result.Close())
  444. }
  445. func TestManager_Token_Extend(t *testing.T) {
  446. a := newTestManager(t, PermissionDenyAll)
  447. require.Nil(t, a.AddUser("ben", "ben", RoleUser))
  448. // Try to extend token for user without token
  449. u, err := a.User("ben")
  450. require.Nil(t, err)
  451. _, err = a.ChangeToken(u.ID, u.Token, util.String("some label"), util.Time(time.Now().Add(time.Hour)))
  452. require.Equal(t, errNoTokenProvided, err)
  453. // Create token for user
  454. token, err := a.CreateToken(u.ID, "", time.Now().Add(72*time.Hour), netip.IPv4Unspecified())
  455. require.Nil(t, err)
  456. require.NotEmpty(t, token.Value)
  457. userWithToken, err := a.AuthenticateToken(token.Value)
  458. require.Nil(t, err)
  459. extendedToken, err := a.ChangeToken(userWithToken.ID, userWithToken.Token, util.String("changed label"), util.Time(time.Now().Add(100*time.Hour)))
  460. require.Nil(t, err)
  461. require.Equal(t, token.Value, extendedToken.Value)
  462. require.Equal(t, "changed label", extendedToken.Label)
  463. require.True(t, token.Expires.Unix() < extendedToken.Expires.Unix())
  464. require.True(t, time.Now().Add(99*time.Hour).Unix() < extendedToken.Expires.Unix())
  465. }
  466. func TestManager_Token_MaxCount_AutoDelete(t *testing.T) {
  467. a := newTestManager(t, PermissionDenyAll)
  468. require.Nil(t, a.AddUser("ben", "ben", RoleUser))
  469. // Try to extend token for user without token
  470. u, err := a.User("ben")
  471. require.Nil(t, err)
  472. // Tokens
  473. baseTime := time.Now().Add(24 * time.Hour)
  474. tokens := make([]string, 0)
  475. for i := 0; i < 22; i++ {
  476. token, err := a.CreateToken(u.ID, "", time.Now().Add(72*time.Hour), netip.IPv4Unspecified())
  477. require.Nil(t, err)
  478. require.NotEmpty(t, token.Value)
  479. tokens = append(tokens, token.Value)
  480. // Manually modify expiry date to avoid sorting issues (this is a hack)
  481. _, err = a.db.Exec(`UPDATE user_token SET expires=? WHERE token=?`, baseTime.Add(time.Duration(i)*time.Minute).Unix(), token.Value)
  482. require.Nil(t, err)
  483. }
  484. _, err = a.AuthenticateToken(tokens[0])
  485. require.Equal(t, ErrUnauthenticated, err)
  486. _, err = a.AuthenticateToken(tokens[1])
  487. require.Equal(t, ErrUnauthenticated, err)
  488. for i := 2; i < 22; i++ {
  489. userWithToken, err := a.AuthenticateToken(tokens[i])
  490. require.Nil(t, err, "token[%d]=%s failed", i, tokens[i])
  491. require.Equal(t, "ben", userWithToken.Name)
  492. require.Equal(t, tokens[i], userWithToken.Token)
  493. }
  494. var count int
  495. rows, err := a.db.Query(`SELECT COUNT(*) FROM user_token`)
  496. require.Nil(t, err)
  497. require.True(t, rows.Next())
  498. require.Nil(t, rows.Scan(&count))
  499. require.Equal(t, 20, count)
  500. }
  501. func TestManager_EnqueueStats_ResetStats(t *testing.T) {
  502. a, err := NewManager(filepath.Join(t.TempDir(), "db"), "", PermissionReadWrite, bcrypt.MinCost, 1500*time.Millisecond)
  503. require.Nil(t, err)
  504. require.Nil(t, a.AddUser("ben", "ben", RoleUser))
  505. // Baseline: No messages or emails
  506. u, err := a.User("ben")
  507. require.Nil(t, err)
  508. require.Equal(t, int64(0), u.Stats.Messages)
  509. require.Equal(t, int64(0), u.Stats.Emails)
  510. a.EnqueueUserStats(u.ID, &Stats{
  511. Messages: 11,
  512. Emails: 2,
  513. })
  514. // Still no change, because it's queued asynchronously
  515. u, err = a.User("ben")
  516. require.Nil(t, err)
  517. require.Equal(t, int64(0), u.Stats.Messages)
  518. require.Equal(t, int64(0), u.Stats.Emails)
  519. // After 2 seconds they should be persisted
  520. time.Sleep(2 * time.Second)
  521. u, err = a.User("ben")
  522. require.Nil(t, err)
  523. require.Equal(t, int64(11), u.Stats.Messages)
  524. require.Equal(t, int64(2), u.Stats.Emails)
  525. // Now reset stats (enqueued stats will be thrown out)
  526. a.EnqueueUserStats(u.ID, &Stats{
  527. Messages: 99,
  528. Emails: 23,
  529. })
  530. require.Nil(t, a.ResetStats())
  531. u, err = a.User("ben")
  532. require.Nil(t, err)
  533. require.Equal(t, int64(0), u.Stats.Messages)
  534. require.Equal(t, int64(0), u.Stats.Emails)
  535. }
  536. func TestManager_EnqueueTokenUpdate(t *testing.T) {
  537. a, err := NewManager(filepath.Join(t.TempDir(), "db"), "", PermissionReadWrite, bcrypt.MinCost, 500*time.Millisecond)
  538. require.Nil(t, err)
  539. require.Nil(t, a.AddUser("ben", "ben", RoleUser))
  540. // Create user and token
  541. u, err := a.User("ben")
  542. require.Nil(t, err)
  543. token, err := a.CreateToken(u.ID, "", time.Now().Add(time.Hour), netip.IPv4Unspecified())
  544. require.Nil(t, err)
  545. // Queue token update
  546. a.EnqueueTokenUpdate(token.Value, &TokenUpdate{
  547. LastAccess: time.Unix(111, 0).UTC(),
  548. LastOrigin: netip.MustParseAddr("1.2.3.3"),
  549. })
  550. // Token has not changed yet.
  551. token2, err := a.Token(u.ID, token.Value)
  552. require.Nil(t, err)
  553. require.Equal(t, token.LastAccess.Unix(), token2.LastAccess.Unix())
  554. require.Equal(t, token.LastOrigin, token2.LastOrigin)
  555. // After a second or so they should be persisted
  556. time.Sleep(time.Second)
  557. token3, err := a.Token(u.ID, token.Value)
  558. require.Nil(t, err)
  559. require.Equal(t, time.Unix(111, 0).UTC().Unix(), token3.LastAccess.Unix())
  560. require.Equal(t, netip.MustParseAddr("1.2.3.3"), token3.LastOrigin)
  561. }
  562. func TestManager_ChangeSettings(t *testing.T) {
  563. a, err := NewManager(filepath.Join(t.TempDir(), "db"), "", PermissionReadWrite, bcrypt.MinCost, 1500*time.Millisecond)
  564. require.Nil(t, err)
  565. require.Nil(t, a.AddUser("ben", "ben", RoleUser))
  566. // No settings
  567. u, err := a.User("ben")
  568. require.Nil(t, err)
  569. require.Nil(t, u.Prefs.Subscriptions)
  570. require.Nil(t, u.Prefs.Notification)
  571. require.Nil(t, u.Prefs.Language)
  572. // Save with new settings
  573. prefs := &Prefs{
  574. Language: util.String("de"),
  575. Notification: &NotificationPrefs{
  576. Sound: util.String("ding"),
  577. MinPriority: util.Int(2),
  578. },
  579. Subscriptions: []*Subscription{
  580. {
  581. BaseURL: "https://ntfy.sh",
  582. Topic: "mytopic",
  583. DisplayName: util.String("My Topic"),
  584. },
  585. },
  586. }
  587. require.Nil(t, a.ChangeSettings(u.ID, prefs))
  588. // Read again
  589. u, err = a.User("ben")
  590. require.Nil(t, err)
  591. require.Equal(t, util.String("de"), u.Prefs.Language)
  592. require.Equal(t, util.String("ding"), u.Prefs.Notification.Sound)
  593. require.Equal(t, util.Int(2), u.Prefs.Notification.MinPriority)
  594. require.Nil(t, u.Prefs.Notification.DeleteAfter)
  595. require.Equal(t, "https://ntfy.sh", u.Prefs.Subscriptions[0].BaseURL)
  596. require.Equal(t, "mytopic", u.Prefs.Subscriptions[0].Topic)
  597. require.Equal(t, util.String("My Topic"), u.Prefs.Subscriptions[0].DisplayName)
  598. }
  599. func TestManager_Tier_Create_Update_List_Delete(t *testing.T) {
  600. a := newTestManager(t, PermissionDenyAll)
  601. // Create tier and user
  602. require.Nil(t, a.AddTier(&Tier{
  603. Code: "supporter",
  604. Name: "Supporter",
  605. MessageLimit: 1,
  606. MessageExpiryDuration: time.Second,
  607. EmailLimit: 1,
  608. ReservationLimit: 1,
  609. AttachmentFileSizeLimit: 1,
  610. AttachmentTotalSizeLimit: 1,
  611. AttachmentExpiryDuration: time.Second,
  612. AttachmentBandwidthLimit: 1,
  613. StripeMonthlyPriceID: "price_1",
  614. }))
  615. require.Nil(t, a.AddTier(&Tier{
  616. Code: "pro",
  617. Name: "Pro",
  618. MessageLimit: 123,
  619. MessageExpiryDuration: 86400 * time.Second,
  620. EmailLimit: 32,
  621. ReservationLimit: 2,
  622. AttachmentFileSizeLimit: 1231231,
  623. AttachmentTotalSizeLimit: 123123,
  624. AttachmentExpiryDuration: 10800 * time.Second,
  625. AttachmentBandwidthLimit: 21474836480,
  626. StripeMonthlyPriceID: "price_2",
  627. }))
  628. require.Nil(t, a.AddUser("phil", "phil", RoleUser))
  629. require.Nil(t, a.ChangeTier("phil", "pro"))
  630. ti, err := a.Tier("pro")
  631. require.Nil(t, err)
  632. u, err := a.User("phil")
  633. require.Nil(t, err)
  634. // These are populated by different SQL queries
  635. require.Equal(t, ti, u.Tier)
  636. // Fields
  637. require.True(t, strings.HasPrefix(ti.ID, "ti_"))
  638. require.Equal(t, "pro", ti.Code)
  639. require.Equal(t, "Pro", ti.Name)
  640. require.Equal(t, int64(123), ti.MessageLimit)
  641. require.Equal(t, 86400*time.Second, ti.MessageExpiryDuration)
  642. require.Equal(t, int64(32), ti.EmailLimit)
  643. require.Equal(t, int64(2), ti.ReservationLimit)
  644. require.Equal(t, int64(1231231), ti.AttachmentFileSizeLimit)
  645. require.Equal(t, int64(123123), ti.AttachmentTotalSizeLimit)
  646. require.Equal(t, 10800*time.Second, ti.AttachmentExpiryDuration)
  647. require.Equal(t, int64(21474836480), ti.AttachmentBandwidthLimit)
  648. require.Equal(t, "price_2", ti.StripeMonthlyPriceID)
  649. // Update tier
  650. ti.EmailLimit = 999999
  651. require.Nil(t, a.UpdateTier(ti))
  652. // List tiers
  653. tiers, err := a.Tiers()
  654. require.Nil(t, err)
  655. require.Equal(t, 2, len(tiers))
  656. ti = tiers[0]
  657. require.Equal(t, "supporter", ti.Code)
  658. require.Equal(t, "Supporter", ti.Name)
  659. require.Equal(t, int64(1), ti.MessageLimit)
  660. require.Equal(t, time.Second, ti.MessageExpiryDuration)
  661. require.Equal(t, int64(1), ti.EmailLimit)
  662. require.Equal(t, int64(1), ti.ReservationLimit)
  663. require.Equal(t, int64(1), ti.AttachmentFileSizeLimit)
  664. require.Equal(t, int64(1), ti.AttachmentTotalSizeLimit)
  665. require.Equal(t, time.Second, ti.AttachmentExpiryDuration)
  666. require.Equal(t, int64(1), ti.AttachmentBandwidthLimit)
  667. require.Equal(t, "price_1", ti.StripeMonthlyPriceID)
  668. ti = tiers[1]
  669. require.Equal(t, "pro", ti.Code)
  670. require.Equal(t, "Pro", ti.Name)
  671. require.Equal(t, int64(123), ti.MessageLimit)
  672. require.Equal(t, 86400*time.Second, ti.MessageExpiryDuration)
  673. require.Equal(t, int64(999999), ti.EmailLimit) // Updatedd!
  674. require.Equal(t, int64(2), ti.ReservationLimit)
  675. require.Equal(t, int64(1231231), ti.AttachmentFileSizeLimit)
  676. require.Equal(t, int64(123123), ti.AttachmentTotalSizeLimit)
  677. require.Equal(t, 10800*time.Second, ti.AttachmentExpiryDuration)
  678. require.Equal(t, int64(21474836480), ti.AttachmentBandwidthLimit)
  679. require.Equal(t, "price_2", ti.StripeMonthlyPriceID)
  680. ti, err = a.TierByStripePrice("price_1")
  681. require.Nil(t, err)
  682. require.Equal(t, "supporter", ti.Code)
  683. require.Equal(t, "Supporter", ti.Name)
  684. require.Equal(t, int64(1), ti.MessageLimit)
  685. require.Equal(t, time.Second, ti.MessageExpiryDuration)
  686. require.Equal(t, int64(1), ti.EmailLimit)
  687. require.Equal(t, int64(1), ti.ReservationLimit)
  688. require.Equal(t, int64(1), ti.AttachmentFileSizeLimit)
  689. require.Equal(t, int64(1), ti.AttachmentTotalSizeLimit)
  690. require.Equal(t, time.Second, ti.AttachmentExpiryDuration)
  691. require.Equal(t, int64(1), ti.AttachmentBandwidthLimit)
  692. require.Equal(t, "price_1", ti.StripeMonthlyPriceID)
  693. // Cannot remove tier, since user has this tier
  694. require.Error(t, a.RemoveTier("pro"))
  695. // CAN remove this tier
  696. require.Nil(t, a.RemoveTier("supporter"))
  697. tiers, err = a.Tiers()
  698. require.Nil(t, err)
  699. require.Equal(t, 1, len(tiers))
  700. require.Equal(t, "pro", tiers[0].Code)
  701. require.Equal(t, "pro", tiers[0].Code)
  702. }
  703. func TestAccount_Tier_Create_With_ID(t *testing.T) {
  704. a := newTestManager(t, PermissionDenyAll)
  705. require.Nil(t, a.AddTier(&Tier{
  706. ID: "ti_123",
  707. Code: "pro",
  708. }))
  709. ti, err := a.Tier("pro")
  710. require.Nil(t, err)
  711. require.Equal(t, "ti_123", ti.ID)
  712. }
  713. func TestManager_Tier_Change_And_Reset(t *testing.T) {
  714. a := newTestManager(t, PermissionDenyAll)
  715. // Create tier and user
  716. require.Nil(t, a.AddTier(&Tier{
  717. Code: "supporter",
  718. Name: "Supporter",
  719. ReservationLimit: 3,
  720. }))
  721. require.Nil(t, a.AddTier(&Tier{
  722. Code: "pro",
  723. Name: "Pro",
  724. ReservationLimit: 4,
  725. }))
  726. require.Nil(t, a.AddUser("phil", "phil", RoleUser))
  727. require.Nil(t, a.ChangeTier("phil", "pro"))
  728. // Add 10 reservations (pro tier allows that)
  729. for i := 0; i < 4; i++ {
  730. require.Nil(t, a.AddReservation("phil", fmt.Sprintf("topic%d", i), PermissionWrite))
  731. }
  732. // Downgrading will not work (too many reservations)
  733. require.Equal(t, ErrTooManyReservations, a.ChangeTier("phil", "supporter"))
  734. // Downgrade after removing a reservation
  735. require.Nil(t, a.RemoveReservations("phil", "topic0"))
  736. require.Nil(t, a.ChangeTier("phil", "supporter"))
  737. // Resetting will not work (too many reservations)
  738. require.Equal(t, ErrTooManyReservations, a.ResetTier("phil"))
  739. // Resetting after removing all reservations
  740. require.Nil(t, a.RemoveReservations("phil", "topic1", "topic2", "topic3"))
  741. require.Nil(t, a.ResetTier("phil"))
  742. }
  743. func TestSqliteCache_Migration_From1(t *testing.T) {
  744. filename := filepath.Join(t.TempDir(), "user.db")
  745. db, err := sql.Open("sqlite3", filename)
  746. require.Nil(t, err)
  747. // Create "version 1" schema
  748. _, err = db.Exec(`
  749. BEGIN;
  750. CREATE TABLE IF NOT EXISTS user (
  751. user TEXT NOT NULL PRIMARY KEY,
  752. pass TEXT NOT NULL,
  753. role TEXT NOT NULL
  754. );
  755. CREATE TABLE IF NOT EXISTS access (
  756. user TEXT NOT NULL,
  757. topic TEXT NOT NULL,
  758. read INT NOT NULL,
  759. write INT NOT NULL,
  760. PRIMARY KEY (topic, user)
  761. );
  762. CREATE TABLE IF NOT EXISTS schemaVersion (
  763. id INT PRIMARY KEY,
  764. version INT NOT NULL
  765. );
  766. INSERT INTO schemaVersion (id, version) VALUES (1, 1);
  767. COMMIT;
  768. `)
  769. require.Nil(t, err)
  770. // Insert a bunch of users and ACL entries
  771. _, err = db.Exec(`
  772. BEGIN;
  773. INSERT INTO user (user, pass, role) VALUES ('ben', '$2a$10$EEp6gBheOsqEFsXlo523E.gBVoeg1ytphXiEvTPlNzkenBlHZBPQy', 'user');
  774. INSERT INTO user (user, pass, role) VALUES ('phil', '$2a$10$YLiO8U21sX1uhZamTLJXHuxgVC0Z/GKISibrKCLohPgtG7yIxSk4C', 'admin');
  775. INSERT INTO access (user, topic, read, write) VALUES ('ben', 'stats', 1, 1);
  776. INSERT INTO access (user, topic, read, write) VALUES ('ben', 'secret', 1, 0);
  777. INSERT INTO access (user, topic, read, write) VALUES ('*', 'stats', 1, 0);
  778. COMMIT;
  779. `)
  780. require.Nil(t, err)
  781. // Create manager to trigger migration
  782. a := newTestManagerFromFile(t, filename, "", PermissionDenyAll, bcrypt.MinCost, DefaultUserStatsQueueWriterInterval)
  783. checkSchemaVersion(t, a.db)
  784. users, err := a.Users()
  785. require.Nil(t, err)
  786. require.Equal(t, 3, len(users))
  787. phil, ben, everyone := users[0], users[1], users[2]
  788. philGrants, err := a.Grants("phil")
  789. require.Nil(t, err)
  790. benGrants, err := a.Grants("ben")
  791. require.Nil(t, err)
  792. everyoneGrants, err := a.Grants(Everyone)
  793. require.Nil(t, err)
  794. require.True(t, strings.HasPrefix(phil.ID, "u_"))
  795. require.Equal(t, "phil", phil.Name)
  796. require.Equal(t, RoleAdmin, phil.Role)
  797. require.Equal(t, syncTopicLength, len(phil.SyncTopic))
  798. require.Equal(t, 0, len(philGrants))
  799. require.True(t, strings.HasPrefix(ben.ID, "u_"))
  800. require.NotEqual(t, phil.ID, ben.ID)
  801. require.Equal(t, "ben", ben.Name)
  802. require.Equal(t, RoleUser, ben.Role)
  803. require.Equal(t, syncTopicLength, len(ben.SyncTopic))
  804. require.NotEqual(t, ben.SyncTopic, phil.SyncTopic)
  805. require.Equal(t, 2, len(benGrants))
  806. require.Equal(t, "stats", benGrants[0].TopicPattern)
  807. require.Equal(t, PermissionReadWrite, benGrants[0].Allow)
  808. require.Equal(t, "secret", benGrants[1].TopicPattern)
  809. require.Equal(t, PermissionRead, benGrants[1].Allow)
  810. require.Equal(t, "u_everyone", everyone.ID)
  811. require.Equal(t, Everyone, everyone.Name)
  812. require.Equal(t, RoleAnonymous, everyone.Role)
  813. require.Equal(t, 1, len(everyoneGrants))
  814. require.Equal(t, "stats", everyoneGrants[0].TopicPattern)
  815. require.Equal(t, PermissionRead, everyoneGrants[0].Allow)
  816. }
  817. func checkSchemaVersion(t *testing.T, db *sql.DB) {
  818. rows, err := db.Query(`SELECT version FROM schemaVersion`)
  819. require.Nil(t, err)
  820. require.True(t, rows.Next())
  821. var schemaVersion int
  822. require.Nil(t, rows.Scan(&schemaVersion))
  823. require.Equal(t, currentSchemaVersion, schemaVersion)
  824. require.Nil(t, rows.Close())
  825. }
  826. func newTestManager(t *testing.T, defaultAccess Permission) *Manager {
  827. return newTestManagerFromFile(t, filepath.Join(t.TempDir(), "user.db"), "", defaultAccess, bcrypt.MinCost, DefaultUserStatsQueueWriterInterval)
  828. }
  829. func newTestManagerFromFile(t *testing.T, filename, startupQueries string, defaultAccess Permission, bcryptCost int, statsWriterInterval time.Duration) *Manager {
  830. a, err := NewManager(filename, startupQueries, defaultAccess, bcryptCost, statsWriterInterval)
  831. require.Nil(t, err)
  832. return a
  833. }