manager_test.go 35 KB

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