manager_test.go 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  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 TestUser_PhoneNumberAddListRemove(t *testing.T) {
  744. a := newTestManager(t, PermissionDenyAll)
  745. require.Nil(t, a.AddUser("phil", "phil", RoleUser))
  746. phil, err := a.User("phil")
  747. require.Nil(t, err)
  748. require.Nil(t, a.AddPhoneNumber(phil.ID, "+1234567890"))
  749. phoneNumbers, err := a.PhoneNumbers(phil.ID)
  750. require.Nil(t, err)
  751. require.Equal(t, 1, len(phoneNumbers))
  752. require.Equal(t, "+1234567890", phoneNumbers[0])
  753. require.Nil(t, a.RemovePhoneNumber(phil.ID, "+1234567890"))
  754. phoneNumbers, err = a.PhoneNumbers(phil.ID)
  755. require.Nil(t, err)
  756. require.Equal(t, 0, len(phoneNumbers))
  757. // Paranoia check: We do NOT want to keep phone numbers in there
  758. rows, err := a.db.Query(`SELECT * FROM user_phone`)
  759. require.Nil(t, err)
  760. require.False(t, rows.Next())
  761. require.Nil(t, rows.Close())
  762. }
  763. func TestUser_PhoneNumberAdd_Multiple_Users_Same_Number(t *testing.T) {
  764. a := newTestManager(t, PermissionDenyAll)
  765. require.Nil(t, a.AddUser("phil", "phil", RoleUser))
  766. require.Nil(t, a.AddUser("ben", "ben", RoleUser))
  767. phil, err := a.User("phil")
  768. require.Nil(t, err)
  769. ben, err := a.User("ben")
  770. require.Nil(t, err)
  771. require.Nil(t, a.AddPhoneNumber(phil.ID, "+1234567890"))
  772. require.Nil(t, a.AddPhoneNumber(ben.ID, "+1234567890"))
  773. }
  774. func TestSqliteCache_Migration_From1(t *testing.T) {
  775. filename := filepath.Join(t.TempDir(), "user.db")
  776. db, err := sql.Open("sqlite3", filename)
  777. require.Nil(t, err)
  778. // Create "version 1" schema
  779. _, err = db.Exec(`
  780. BEGIN;
  781. CREATE TABLE IF NOT EXISTS user (
  782. user TEXT NOT NULL PRIMARY KEY,
  783. pass TEXT NOT NULL,
  784. role TEXT NOT NULL
  785. );
  786. CREATE TABLE IF NOT EXISTS access (
  787. user TEXT NOT NULL,
  788. topic TEXT NOT NULL,
  789. read INT NOT NULL,
  790. write INT NOT NULL,
  791. PRIMARY KEY (topic, user)
  792. );
  793. CREATE TABLE IF NOT EXISTS schemaVersion (
  794. id INT PRIMARY KEY,
  795. version INT NOT NULL
  796. );
  797. INSERT INTO schemaVersion (id, version) VALUES (1, 1);
  798. COMMIT;
  799. `)
  800. require.Nil(t, err)
  801. // Insert a bunch of users and ACL entries
  802. _, err = db.Exec(`
  803. BEGIN;
  804. INSERT INTO user (user, pass, role) VALUES ('ben', '$2a$10$EEp6gBheOsqEFsXlo523E.gBVoeg1ytphXiEvTPlNzkenBlHZBPQy', 'user');
  805. INSERT INTO user (user, pass, role) VALUES ('phil', '$2a$10$YLiO8U21sX1uhZamTLJXHuxgVC0Z/GKISibrKCLohPgtG7yIxSk4C', 'admin');
  806. INSERT INTO access (user, topic, read, write) VALUES ('ben', 'stats', 1, 1);
  807. INSERT INTO access (user, topic, read, write) VALUES ('ben', 'secret', 1, 0);
  808. INSERT INTO access (user, topic, read, write) VALUES ('*', 'stats', 1, 0);
  809. COMMIT;
  810. `)
  811. require.Nil(t, err)
  812. // Create manager to trigger migration
  813. a := newTestManagerFromFile(t, filename, "", PermissionDenyAll, bcrypt.MinCost, DefaultUserStatsQueueWriterInterval)
  814. checkSchemaVersion(t, a.db)
  815. users, err := a.Users()
  816. require.Nil(t, err)
  817. require.Equal(t, 3, len(users))
  818. phil, ben, everyone := users[0], users[1], users[2]
  819. philGrants, err := a.Grants("phil")
  820. require.Nil(t, err)
  821. benGrants, err := a.Grants("ben")
  822. require.Nil(t, err)
  823. everyoneGrants, err := a.Grants(Everyone)
  824. require.Nil(t, err)
  825. require.True(t, strings.HasPrefix(phil.ID, "u_"))
  826. require.Equal(t, "phil", phil.Name)
  827. require.Equal(t, RoleAdmin, phil.Role)
  828. require.Equal(t, syncTopicLength, len(phil.SyncTopic))
  829. require.Equal(t, 0, len(philGrants))
  830. require.True(t, strings.HasPrefix(ben.ID, "u_"))
  831. require.NotEqual(t, phil.ID, ben.ID)
  832. require.Equal(t, "ben", ben.Name)
  833. require.Equal(t, RoleUser, ben.Role)
  834. require.Equal(t, syncTopicLength, len(ben.SyncTopic))
  835. require.NotEqual(t, ben.SyncTopic, phil.SyncTopic)
  836. require.Equal(t, 2, len(benGrants))
  837. require.Equal(t, "stats", benGrants[0].TopicPattern)
  838. require.Equal(t, PermissionReadWrite, benGrants[0].Allow)
  839. require.Equal(t, "secret", benGrants[1].TopicPattern)
  840. require.Equal(t, PermissionRead, benGrants[1].Allow)
  841. require.Equal(t, "u_everyone", everyone.ID)
  842. require.Equal(t, Everyone, everyone.Name)
  843. require.Equal(t, RoleAnonymous, everyone.Role)
  844. require.Equal(t, 1, len(everyoneGrants))
  845. require.Equal(t, "stats", everyoneGrants[0].TopicPattern)
  846. require.Equal(t, PermissionRead, everyoneGrants[0].Allow)
  847. }
  848. func checkSchemaVersion(t *testing.T, db *sql.DB) {
  849. rows, err := db.Query(`SELECT version FROM schemaVersion`)
  850. require.Nil(t, err)
  851. require.True(t, rows.Next())
  852. var schemaVersion int
  853. require.Nil(t, rows.Scan(&schemaVersion))
  854. require.Equal(t, currentSchemaVersion, schemaVersion)
  855. require.Nil(t, rows.Close())
  856. }
  857. func newTestManager(t *testing.T, defaultAccess Permission) *Manager {
  858. return newTestManagerFromFile(t, filepath.Join(t.TempDir(), "user.db"), "", defaultAccess, bcrypt.MinCost, DefaultUserStatsQueueWriterInterval)
  859. }
  860. func newTestManagerFromFile(t *testing.T, filename, startupQueries string, defaultAccess Permission, bcryptCost int, statsWriterInterval time.Duration) *Manager {
  861. a, err := NewManager(filename, startupQueries, defaultAccess, bcryptCost, statsWriterInterval)
  862. require.Nil(t, err)
  863. return a
  864. }