manager_test.go 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332
  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/v2/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.AddUser("john", "john", RoleUser))
  21. require.Nil(t, a.AllowAccess("ben", "mytopic", PermissionReadWrite))
  22. require.Nil(t, a.AllowAccess("ben", "readme", PermissionRead))
  23. require.Nil(t, a.AllowAccess("ben", "writeme", PermissionWrite))
  24. require.Nil(t, a.AllowAccess("ben", "everyonewrite", PermissionDenyAll)) // How unfair!
  25. require.Nil(t, a.AllowAccess("john", "*", PermissionRead))
  26. require.Nil(t, a.AllowAccess("john", "mytopic*", PermissionReadWrite))
  27. require.Nil(t, a.AllowAccess("john", "mytopic_ro*", PermissionRead))
  28. require.Nil(t, a.AllowAccess("john", "mytopic_deny*", PermissionDenyAll))
  29. require.Nil(t, a.AllowAccess(Everyone, "announcements", PermissionRead))
  30. require.Nil(t, a.AllowAccess(Everyone, "everyonewrite", PermissionReadWrite))
  31. require.Nil(t, a.AllowAccess(Everyone, "up*", PermissionWrite)) // Everyone can write to /up*
  32. phil, err := a.Authenticate("phil", "phil")
  33. require.Nil(t, err)
  34. require.Equal(t, "phil", phil.Name)
  35. require.True(t, strings.HasPrefix(phil.Hash, "$2a$10$"))
  36. require.Equal(t, RoleAdmin, phil.Role)
  37. philGrants, err := a.Grants("phil")
  38. require.Nil(t, err)
  39. require.Equal(t, []Grant{}, philGrants)
  40. ben, err := a.Authenticate("ben", "ben")
  41. require.Nil(t, err)
  42. require.Equal(t, "ben", ben.Name)
  43. require.True(t, strings.HasPrefix(ben.Hash, "$2a$10$"))
  44. require.Equal(t, RoleUser, ben.Role)
  45. benGrants, err := a.Grants("ben")
  46. require.Nil(t, err)
  47. require.Equal(t, []Grant{
  48. {"everyonewrite", PermissionDenyAll},
  49. {"mytopic", PermissionReadWrite},
  50. {"writeme", PermissionWrite},
  51. {"readme", PermissionRead},
  52. }, benGrants)
  53. john, err := a.Authenticate("john", "john")
  54. require.Nil(t, err)
  55. require.Equal(t, "john", john.Name)
  56. require.True(t, strings.HasPrefix(john.Hash, "$2a$10$"))
  57. require.Equal(t, RoleUser, john.Role)
  58. johnGrants, err := a.Grants("john")
  59. require.Nil(t, err)
  60. require.Equal(t, []Grant{
  61. {"mytopic_deny*", PermissionDenyAll},
  62. {"mytopic_ro*", PermissionRead},
  63. {"mytopic*", PermissionReadWrite},
  64. {"*", PermissionRead},
  65. }, johnGrants)
  66. notben, err := a.Authenticate("ben", "this is wrong")
  67. require.Nil(t, notben)
  68. require.Equal(t, ErrUnauthenticated, err)
  69. // Admin can do everything
  70. require.Nil(t, a.Authorize(phil, "sometopic", PermissionWrite))
  71. require.Nil(t, a.Authorize(phil, "mytopic", PermissionRead))
  72. require.Nil(t, a.Authorize(phil, "readme", PermissionWrite))
  73. require.Nil(t, a.Authorize(phil, "writeme", PermissionWrite))
  74. require.Nil(t, a.Authorize(phil, "announcements", PermissionWrite))
  75. require.Nil(t, a.Authorize(phil, "everyonewrite", PermissionWrite))
  76. // User cannot do everything
  77. require.Nil(t, a.Authorize(ben, "mytopic", PermissionWrite))
  78. require.Nil(t, a.Authorize(ben, "mytopic", PermissionRead))
  79. require.Nil(t, a.Authorize(ben, "readme", PermissionRead))
  80. require.Equal(t, ErrUnauthorized, a.Authorize(ben, "readme", PermissionWrite))
  81. require.Equal(t, ErrUnauthorized, a.Authorize(ben, "writeme", PermissionRead))
  82. require.Nil(t, a.Authorize(ben, "writeme", PermissionWrite))
  83. require.Nil(t, a.Authorize(ben, "writeme", PermissionWrite))
  84. require.Equal(t, ErrUnauthorized, a.Authorize(ben, "everyonewrite", PermissionRead))
  85. require.Equal(t, ErrUnauthorized, a.Authorize(ben, "everyonewrite", PermissionWrite))
  86. require.Nil(t, a.Authorize(ben, "announcements", PermissionRead))
  87. require.Equal(t, ErrUnauthorized, a.Authorize(ben, "announcements", PermissionWrite))
  88. // User john should have
  89. // "deny" to mytopic_deny*,
  90. // "ro" to mytopic_ro*,
  91. // "rw" to mytopic*,
  92. // "ro" to the rest
  93. require.Equal(t, ErrUnauthorized, a.Authorize(john, "mytopic_deny_case", PermissionRead))
  94. require.Equal(t, ErrUnauthorized, a.Authorize(john, "mytopic_deny_case", PermissionWrite))
  95. require.Nil(t, a.Authorize(john, "mytopic_ro_test_case", PermissionRead))
  96. require.Equal(t, ErrUnauthorized, a.Authorize(john, "mytopic_ro_test_case", PermissionWrite))
  97. require.Nil(t, a.Authorize(john, "mytopic_case1", PermissionRead))
  98. require.Nil(t, a.Authorize(john, "mytopic_case1", PermissionWrite))
  99. require.Nil(t, a.Authorize(john, "readme", PermissionRead))
  100. require.Equal(t, ErrUnauthorized, a.Authorize(john, "writeme", PermissionWrite))
  101. // Everyone else can do barely anything
  102. require.Equal(t, ErrUnauthorized, a.Authorize(nil, "sometopicnotinthelist", PermissionRead))
  103. require.Equal(t, ErrUnauthorized, a.Authorize(nil, "sometopicnotinthelist", PermissionWrite))
  104. require.Equal(t, ErrUnauthorized, a.Authorize(nil, "mytopic", PermissionRead))
  105. require.Equal(t, ErrUnauthorized, a.Authorize(nil, "mytopic", PermissionWrite))
  106. require.Equal(t, ErrUnauthorized, a.Authorize(nil, "readme", PermissionRead))
  107. require.Equal(t, ErrUnauthorized, a.Authorize(nil, "readme", PermissionWrite))
  108. require.Equal(t, ErrUnauthorized, a.Authorize(nil, "writeme", PermissionRead))
  109. require.Equal(t, ErrUnauthorized, a.Authorize(nil, "writeme", PermissionWrite))
  110. require.Equal(t, ErrUnauthorized, a.Authorize(nil, "announcements", PermissionWrite))
  111. require.Nil(t, a.Authorize(nil, "announcements", PermissionRead))
  112. require.Nil(t, a.Authorize(nil, "everyonewrite", PermissionRead))
  113. require.Nil(t, a.Authorize(nil, "everyonewrite", PermissionWrite))
  114. require.Nil(t, a.Authorize(nil, "up1234", PermissionWrite)) // Wildcard permission
  115. require.Nil(t, a.Authorize(nil, "up5678", PermissionWrite))
  116. }
  117. func TestManager_Access_Order_LengthWriteRead(t *testing.T) {
  118. // This test validates issue #914 / #917, i.e. that write permissions are prioritized over read permissions,
  119. // and longer ACL rules are prioritized as well.
  120. a := newTestManagerFromFile(t, filepath.Join(t.TempDir(), "user.db"), "", PermissionDenyAll, DefaultUserPasswordBcryptCost, DefaultUserStatsQueueWriterInterval)
  121. require.Nil(t, a.AddUser("ben", "ben", RoleUser))
  122. require.Nil(t, a.AllowAccess("ben", "test*", PermissionReadWrite))
  123. require.Nil(t, a.AllowAccess("ben", "*", PermissionRead))
  124. ben, err := a.Authenticate("ben", "ben")
  125. require.Nil(t, err)
  126. require.Nil(t, a.Authorize(ben, "any-topic-can-be-read", PermissionRead))
  127. require.Nil(t, a.Authorize(ben, "this-too", PermissionRead))
  128. require.Nil(t, a.Authorize(ben, "test123", PermissionWrite))
  129. }
  130. func TestManager_AddUser_Invalid(t *testing.T) {
  131. a := newTestManager(t, PermissionDenyAll)
  132. require.Equal(t, ErrInvalidArgument, a.AddUser(" invalid ", "pass", RoleAdmin))
  133. require.Equal(t, ErrInvalidArgument, a.AddUser("validuser", "pass", "invalid-role"))
  134. }
  135. func TestManager_AddUser_Timing(t *testing.T) {
  136. a := newTestManagerFromFile(t, filepath.Join(t.TempDir(), "user.db"), "", PermissionDenyAll, DefaultUserPasswordBcryptCost, DefaultUserStatsQueueWriterInterval)
  137. start := time.Now().UnixMilli()
  138. require.Nil(t, a.AddUser("user", "pass", RoleAdmin))
  139. require.GreaterOrEqual(t, time.Now().UnixMilli()-start, minBcryptTimingMillis)
  140. }
  141. func TestManager_AddUser_And_Query(t *testing.T) {
  142. a := newTestManagerFromFile(t, filepath.Join(t.TempDir(), "user.db"), "", PermissionDenyAll, DefaultUserPasswordBcryptCost, DefaultUserStatsQueueWriterInterval)
  143. require.Nil(t, a.AddUser("user", "pass", RoleAdmin))
  144. require.Nil(t, a.ChangeBilling("user", &Billing{
  145. StripeCustomerID: "acct_123",
  146. StripeSubscriptionID: "sub_123",
  147. StripeSubscriptionStatus: stripe.SubscriptionStatusActive,
  148. StripeSubscriptionInterval: stripe.PriceRecurringIntervalMonth,
  149. StripeSubscriptionPaidUntil: time.Now().Add(time.Hour),
  150. StripeSubscriptionCancelAt: time.Unix(0, 0),
  151. }))
  152. u, err := a.User("user")
  153. require.Nil(t, err)
  154. require.Equal(t, "user", u.Name)
  155. u2, err := a.UserByID(u.ID)
  156. require.Nil(t, err)
  157. require.Equal(t, u.Name, u2.Name)
  158. u3, err := a.UserByStripeCustomer("acct_123")
  159. require.Nil(t, err)
  160. require.Equal(t, u.ID, u3.ID)
  161. }
  162. func TestManager_MarkUserRemoved_RemoveDeletedUsers(t *testing.T) {
  163. a := newTestManager(t, PermissionDenyAll)
  164. // Create user, add reservations and token
  165. require.Nil(t, a.AddUser("user", "pass", RoleAdmin))
  166. require.Nil(t, a.AddReservation("user", "mytopic", PermissionRead))
  167. u, err := a.User("user")
  168. require.Nil(t, err)
  169. require.False(t, u.Deleted)
  170. token, err := a.CreateToken(u.ID, "", time.Now().Add(time.Hour), netip.IPv4Unspecified())
  171. require.Nil(t, err)
  172. u, err = a.Authenticate("user", "pass")
  173. require.Nil(t, err)
  174. _, err = a.AuthenticateToken(token.Value)
  175. require.Nil(t, err)
  176. reservations, err := a.Reservations("user")
  177. require.Nil(t, err)
  178. require.Equal(t, 1, len(reservations))
  179. // Mark deleted: cannot auth anymore, and all reservations are gone
  180. require.Nil(t, a.MarkUserRemoved(u))
  181. _, err = a.Authenticate("user", "pass")
  182. require.Equal(t, ErrUnauthenticated, err)
  183. _, err = a.AuthenticateToken(token.Value)
  184. require.Equal(t, ErrUnauthenticated, err)
  185. reservations, err = a.Reservations("user")
  186. require.Nil(t, err)
  187. require.Equal(t, 0, len(reservations))
  188. // Make sure user is still there
  189. u, err = a.User("user")
  190. require.Nil(t, err)
  191. require.True(t, u.Deleted)
  192. _, err = a.db.Exec("UPDATE user SET deleted = ? WHERE id = ?", time.Now().Add(-1*(userHardDeleteAfterDuration+time.Hour)).Unix(), u.ID)
  193. require.Nil(t, err)
  194. require.Nil(t, a.RemoveDeletedUsers())
  195. _, err = a.User("user")
  196. require.Equal(t, ErrUserNotFound, err)
  197. }
  198. func TestManager_CreateToken_Only_Lower(t *testing.T) {
  199. a := newTestManager(t, PermissionDenyAll)
  200. // Create user, add reservations and token
  201. require.Nil(t, a.AddUser("user", "pass", RoleAdmin))
  202. u, err := a.User("user")
  203. require.Nil(t, err)
  204. token, err := a.CreateToken(u.ID, "", time.Now().Add(time.Hour), netip.IPv4Unspecified())
  205. require.Nil(t, err)
  206. require.Equal(t, token.Value, strings.ToLower(token.Value))
  207. }
  208. func TestManager_UserManagement(t *testing.T) {
  209. a := newTestManager(t, PermissionDenyAll)
  210. require.Nil(t, a.AddUser("phil", "phil", RoleAdmin))
  211. require.Nil(t, a.AddUser("ben", "ben", RoleUser))
  212. require.Nil(t, a.AllowAccess("ben", "mytopic", PermissionReadWrite))
  213. require.Nil(t, a.AllowAccess("ben", "readme", PermissionRead))
  214. require.Nil(t, a.AllowAccess("ben", "writeme", PermissionWrite))
  215. require.Nil(t, a.AllowAccess("ben", "everyonewrite", PermissionDenyAll)) // How unfair!
  216. require.Nil(t, a.AllowAccess(Everyone, "announcements", PermissionRead))
  217. require.Nil(t, a.AllowAccess(Everyone, "everyonewrite", PermissionReadWrite))
  218. // Query user details
  219. phil, err := a.User("phil")
  220. require.Nil(t, err)
  221. require.Equal(t, "phil", phil.Name)
  222. require.True(t, strings.HasPrefix(phil.Hash, "$2a$04$")) // Min cost for testing
  223. require.Equal(t, RoleAdmin, phil.Role)
  224. philGrants, err := a.Grants("phil")
  225. require.Nil(t, err)
  226. require.Equal(t, []Grant{}, philGrants)
  227. ben, err := a.User("ben")
  228. require.Nil(t, err)
  229. require.Equal(t, "ben", ben.Name)
  230. require.True(t, strings.HasPrefix(ben.Hash, "$2a$04$")) // Min cost for testing
  231. require.Equal(t, RoleUser, ben.Role)
  232. benGrants, err := a.Grants("ben")
  233. require.Nil(t, err)
  234. require.Equal(t, []Grant{
  235. {"everyonewrite", PermissionDenyAll},
  236. {"mytopic", PermissionReadWrite},
  237. {"writeme", PermissionWrite},
  238. {"readme", PermissionRead},
  239. }, benGrants)
  240. everyone, err := a.User(Everyone)
  241. require.Nil(t, err)
  242. require.Equal(t, "*", everyone.Name)
  243. require.Equal(t, "", everyone.Hash)
  244. require.Equal(t, RoleAnonymous, everyone.Role)
  245. everyoneGrants, err := a.Grants(Everyone)
  246. require.Nil(t, err)
  247. require.Equal(t, []Grant{
  248. {"everyonewrite", PermissionReadWrite},
  249. {"announcements", PermissionRead},
  250. }, everyoneGrants)
  251. // Ben: Before revoking
  252. require.Nil(t, a.AllowAccess("ben", "mytopic", PermissionReadWrite)) // Overwrite!
  253. require.Nil(t, a.AllowAccess("ben", "readme", PermissionRead))
  254. require.Nil(t, a.AllowAccess("ben", "writeme", PermissionWrite))
  255. require.Nil(t, a.Authorize(ben, "mytopic", PermissionRead))
  256. require.Nil(t, a.Authorize(ben, "mytopic", PermissionWrite))
  257. require.Nil(t, a.Authorize(ben, "readme", PermissionRead))
  258. require.Nil(t, a.Authorize(ben, "writeme", PermissionWrite))
  259. // Revoke access for "ben" to "mytopic", then check again
  260. require.Nil(t, a.ResetAccess("ben", "mytopic"))
  261. require.Equal(t, ErrUnauthorized, a.Authorize(ben, "mytopic", PermissionWrite)) // Revoked
  262. require.Equal(t, ErrUnauthorized, a.Authorize(ben, "mytopic", PermissionRead)) // Revoked
  263. require.Nil(t, a.Authorize(ben, "readme", PermissionRead)) // Unchanged
  264. require.Nil(t, a.Authorize(ben, "writeme", PermissionWrite)) // Unchanged
  265. // Revoke rest of the access
  266. require.Nil(t, a.ResetAccess("ben", ""))
  267. require.Equal(t, ErrUnauthorized, a.Authorize(ben, "readme", PermissionRead)) // Revoked
  268. require.Equal(t, ErrUnauthorized, a.Authorize(ben, "wrtiteme", PermissionWrite)) // Revoked
  269. // User list
  270. users, err := a.Users()
  271. require.Nil(t, err)
  272. require.Equal(t, 3, len(users))
  273. require.Equal(t, "phil", users[0].Name)
  274. require.Equal(t, "ben", users[1].Name)
  275. require.Equal(t, "*", users[2].Name)
  276. // Remove user
  277. require.Nil(t, a.RemoveUser("ben"))
  278. _, err = a.User("ben")
  279. require.Equal(t, ErrUserNotFound, err)
  280. users, err = a.Users()
  281. require.Nil(t, err)
  282. require.Equal(t, 2, len(users))
  283. require.Equal(t, "phil", users[0].Name)
  284. require.Equal(t, "*", users[1].Name)
  285. }
  286. func TestManager_ChangePassword(t *testing.T) {
  287. a := newTestManager(t, PermissionDenyAll)
  288. require.Nil(t, a.AddUser("phil", "phil", RoleAdmin))
  289. _, err := a.Authenticate("phil", "phil")
  290. require.Nil(t, err)
  291. require.Nil(t, a.ChangePassword("phil", "newpass"))
  292. _, err = a.Authenticate("phil", "phil")
  293. require.Equal(t, ErrUnauthenticated, err)
  294. _, err = a.Authenticate("phil", "newpass")
  295. require.Nil(t, err)
  296. }
  297. func TestManager_ChangeRole(t *testing.T) {
  298. a := newTestManager(t, PermissionDenyAll)
  299. require.Nil(t, a.AddUser("ben", "ben", RoleUser))
  300. require.Nil(t, a.AllowAccess("ben", "mytopic", PermissionReadWrite))
  301. require.Nil(t, a.AllowAccess("ben", "readme", PermissionRead))
  302. ben, err := a.User("ben")
  303. require.Nil(t, err)
  304. require.Equal(t, RoleUser, ben.Role)
  305. benGrants, err := a.Grants("ben")
  306. require.Nil(t, err)
  307. require.Equal(t, 2, len(benGrants))
  308. require.Nil(t, a.ChangeRole("ben", RoleAdmin))
  309. ben, err = a.User("ben")
  310. require.Nil(t, err)
  311. require.Equal(t, RoleAdmin, ben.Role)
  312. benGrants, err = a.Grants("ben")
  313. require.Nil(t, err)
  314. require.Equal(t, 0, len(benGrants))
  315. }
  316. func TestManager_Reservations(t *testing.T) {
  317. a := newTestManager(t, PermissionDenyAll)
  318. require.Nil(t, a.AddUser("phil", "phil", RoleUser))
  319. require.Nil(t, a.AddUser("ben", "ben", RoleUser))
  320. require.Nil(t, a.AddReservation("ben", "ztopic_", PermissionDenyAll))
  321. require.Nil(t, a.AddReservation("ben", "readme", PermissionRead))
  322. require.Nil(t, a.AllowAccess("ben", "something-else", PermissionRead))
  323. reservations, err := a.Reservations("ben")
  324. require.Nil(t, err)
  325. require.Equal(t, 2, len(reservations))
  326. require.Equal(t, Reservation{
  327. Topic: "readme",
  328. Owner: PermissionReadWrite,
  329. Everyone: PermissionRead,
  330. }, reservations[0])
  331. require.Equal(t, Reservation{
  332. Topic: "ztopic_",
  333. Owner: PermissionReadWrite,
  334. Everyone: PermissionDenyAll,
  335. }, reservations[1])
  336. b, err := a.HasReservation("ben", "readme")
  337. require.Nil(t, err)
  338. require.True(t, b)
  339. b, err = a.HasReservation("ben", "ztopic_")
  340. require.Nil(t, err)
  341. require.True(t, b)
  342. b, err = a.HasReservation("ben", "ztopicX") // _ != X (used to be a SQL wildcard issue)
  343. require.Nil(t, err)
  344. require.False(t, b)
  345. b, err = a.HasReservation("notben", "readme")
  346. require.Nil(t, err)
  347. require.False(t, b)
  348. b, err = a.HasReservation("ben", "something-else")
  349. require.Nil(t, err)
  350. require.False(t, b)
  351. count, err := a.ReservationsCount("ben")
  352. require.Nil(t, err)
  353. require.Equal(t, int64(2), count)
  354. count, err = a.ReservationsCount("phil")
  355. require.Nil(t, err)
  356. require.Equal(t, int64(0), count)
  357. err = a.AllowReservation("phil", "readme")
  358. require.Equal(t, errTopicOwnedByOthers, err)
  359. err = a.AllowReservation("phil", "ztopic_")
  360. require.Equal(t, errTopicOwnedByOthers, err)
  361. err = a.AllowReservation("phil", "ztopicX")
  362. require.Nil(t, err)
  363. err = a.AllowReservation("phil", "not-reserved")
  364. require.Nil(t, err)
  365. // Now remove them again
  366. require.Nil(t, a.RemoveReservations("ben", "ztopic_", "readme"))
  367. count, err = a.ReservationsCount("ben")
  368. require.Nil(t, err)
  369. require.Equal(t, int64(0), count)
  370. }
  371. func TestManager_ChangeRoleFromTierUserToAdmin(t *testing.T) {
  372. a := newTestManager(t, PermissionDenyAll)
  373. require.Nil(t, a.AddTier(&Tier{
  374. Code: "pro",
  375. Name: "ntfy Pro",
  376. StripeMonthlyPriceID: "price123",
  377. MessageLimit: 5_000,
  378. MessageExpiryDuration: 3 * 24 * time.Hour,
  379. EmailLimit: 50,
  380. ReservationLimit: 5,
  381. AttachmentFileSizeLimit: 52428800,
  382. AttachmentTotalSizeLimit: 524288000,
  383. AttachmentExpiryDuration: 24 * time.Hour,
  384. }))
  385. require.Nil(t, a.AddUser("ben", "ben", RoleUser))
  386. require.Nil(t, a.ChangeTier("ben", "pro"))
  387. require.Nil(t, a.AddReservation("ben", "mytopic", PermissionDenyAll))
  388. ben, err := a.User("ben")
  389. require.Nil(t, err)
  390. require.Equal(t, RoleUser, ben.Role)
  391. require.Equal(t, "pro", ben.Tier.Code)
  392. require.Equal(t, int64(5000), ben.Tier.MessageLimit)
  393. require.Equal(t, 3*24*time.Hour, ben.Tier.MessageExpiryDuration)
  394. require.Equal(t, int64(50), ben.Tier.EmailLimit)
  395. require.Equal(t, int64(5), ben.Tier.ReservationLimit)
  396. require.Equal(t, int64(52428800), ben.Tier.AttachmentFileSizeLimit)
  397. require.Equal(t, int64(524288000), ben.Tier.AttachmentTotalSizeLimit)
  398. require.Equal(t, 24*time.Hour, ben.Tier.AttachmentExpiryDuration)
  399. benGrants, err := a.Grants("ben")
  400. require.Nil(t, err)
  401. require.Equal(t, 1, len(benGrants))
  402. require.Equal(t, PermissionReadWrite, benGrants[0].Allow)
  403. everyoneGrants, err := a.Grants(Everyone)
  404. require.Nil(t, err)
  405. require.Equal(t, 1, len(everyoneGrants))
  406. require.Equal(t, PermissionDenyAll, everyoneGrants[0].Allow)
  407. benReservations, err := a.Reservations("ben")
  408. require.Nil(t, err)
  409. require.Equal(t, 1, len(benReservations))
  410. require.Equal(t, "mytopic", benReservations[0].Topic)
  411. require.Equal(t, PermissionReadWrite, benReservations[0].Owner)
  412. require.Equal(t, PermissionDenyAll, benReservations[0].Everyone)
  413. // Switch to admin, this should remove all grants and owned ACL entries
  414. require.Nil(t, a.ChangeRole("ben", RoleAdmin))
  415. benGrants, err = a.Grants("ben")
  416. require.Nil(t, err)
  417. require.Equal(t, 0, len(benGrants))
  418. everyoneGrants, err = a.Grants(Everyone)
  419. require.Nil(t, err)
  420. require.Equal(t, 0, len(everyoneGrants))
  421. }
  422. func TestManager_Token_Valid(t *testing.T) {
  423. a := newTestManager(t, PermissionDenyAll)
  424. require.Nil(t, a.AddUser("ben", "ben", RoleUser))
  425. u, err := a.User("ben")
  426. require.Nil(t, err)
  427. // Create token for user
  428. token, err := a.CreateToken(u.ID, "some label", time.Now().Add(72*time.Hour), netip.IPv4Unspecified())
  429. require.Nil(t, err)
  430. require.NotEmpty(t, token.Value)
  431. require.Equal(t, "some label", token.Label)
  432. require.True(t, time.Now().Add(71*time.Hour).Unix() < token.Expires.Unix())
  433. u2, err := a.AuthenticateToken(token.Value)
  434. require.Nil(t, err)
  435. require.Equal(t, u.Name, u2.Name)
  436. require.Equal(t, token.Value, u2.Token)
  437. token2, err := a.Token(u.ID, token.Value)
  438. require.Nil(t, err)
  439. require.Equal(t, token.Value, token2.Value)
  440. require.Equal(t, "some label", token2.Label)
  441. tokens, err := a.Tokens(u.ID)
  442. require.Nil(t, err)
  443. require.Equal(t, 1, len(tokens))
  444. require.Equal(t, "some label", tokens[0].Label)
  445. tokens, err = a.Tokens("u_notauser")
  446. require.Nil(t, err)
  447. require.Equal(t, 0, len(tokens))
  448. // Remove token and auth again
  449. require.Nil(t, a.RemoveToken(u2.ID, u2.Token))
  450. u3, err := a.AuthenticateToken(token.Value)
  451. require.Equal(t, ErrUnauthenticated, err)
  452. require.Nil(t, u3)
  453. tokens, err = a.Tokens(u.ID)
  454. require.Nil(t, err)
  455. require.Equal(t, 0, len(tokens))
  456. }
  457. func TestManager_Token_Invalid(t *testing.T) {
  458. a := newTestManager(t, PermissionDenyAll)
  459. require.Nil(t, a.AddUser("ben", "ben", RoleUser))
  460. u, err := a.AuthenticateToken(strings.Repeat("x", 32)) // 32 == token length
  461. require.Nil(t, u)
  462. require.Equal(t, ErrUnauthenticated, err)
  463. u, err = a.AuthenticateToken("not long enough anyway")
  464. require.Nil(t, u)
  465. require.Equal(t, ErrUnauthenticated, err)
  466. }
  467. func TestManager_Token_NotFound(t *testing.T) {
  468. a := newTestManager(t, PermissionDenyAll)
  469. _, err := a.Token("u_bla", "notfound")
  470. require.Equal(t, ErrTokenNotFound, err)
  471. }
  472. func TestManager_Token_Expire(t *testing.T) {
  473. a := newTestManager(t, PermissionDenyAll)
  474. require.Nil(t, a.AddUser("ben", "ben", RoleUser))
  475. u, err := a.User("ben")
  476. require.Nil(t, err)
  477. // Create tokens for user
  478. token1, err := a.CreateToken(u.ID, "", time.Now().Add(72*time.Hour), netip.IPv4Unspecified())
  479. require.Nil(t, err)
  480. require.NotEmpty(t, token1.Value)
  481. require.True(t, time.Now().Add(71*time.Hour).Unix() < token1.Expires.Unix())
  482. token2, err := a.CreateToken(u.ID, "", time.Now().Add(72*time.Hour), netip.IPv4Unspecified())
  483. require.Nil(t, err)
  484. require.NotEmpty(t, token2.Value)
  485. require.NotEqual(t, token1.Value, token2.Value)
  486. require.True(t, time.Now().Add(71*time.Hour).Unix() < token2.Expires.Unix())
  487. // See that tokens work
  488. _, err = a.AuthenticateToken(token1.Value)
  489. require.Nil(t, err)
  490. _, err = a.AuthenticateToken(token2.Value)
  491. require.Nil(t, err)
  492. // Modify token expiration in database
  493. _, err = a.db.Exec("UPDATE user_token SET expires = 1 WHERE token = ?", token1.Value)
  494. require.Nil(t, err)
  495. // Now token1 shouldn't work anymore
  496. _, err = a.AuthenticateToken(token1.Value)
  497. require.Equal(t, ErrUnauthenticated, err)
  498. result, err := a.db.Query("SELECT * from user_token WHERE token = ?", token1.Value)
  499. require.Nil(t, err)
  500. require.True(t, result.Next()) // Still a matching row
  501. require.Nil(t, result.Close())
  502. // Expire tokens and check database rows
  503. require.Nil(t, a.RemoveExpiredTokens())
  504. result, err = a.db.Query("SELECT * from user_token WHERE token = ?", token1.Value)
  505. require.Nil(t, err)
  506. require.False(t, result.Next()) // No matching row!
  507. require.Nil(t, result.Close())
  508. }
  509. func TestManager_Token_Extend(t *testing.T) {
  510. a := newTestManager(t, PermissionDenyAll)
  511. require.Nil(t, a.AddUser("ben", "ben", RoleUser))
  512. // Try to extend token for user without token
  513. u, err := a.User("ben")
  514. require.Nil(t, err)
  515. _, err = a.ChangeToken(u.ID, u.Token, util.String("some label"), util.Time(time.Now().Add(time.Hour)))
  516. require.Equal(t, errNoTokenProvided, err)
  517. // Create token for user
  518. token, err := a.CreateToken(u.ID, "", time.Now().Add(72*time.Hour), netip.IPv4Unspecified())
  519. require.Nil(t, err)
  520. require.NotEmpty(t, token.Value)
  521. userWithToken, err := a.AuthenticateToken(token.Value)
  522. require.Nil(t, err)
  523. extendedToken, err := a.ChangeToken(userWithToken.ID, userWithToken.Token, util.String("changed label"), util.Time(time.Now().Add(100*time.Hour)))
  524. require.Nil(t, err)
  525. require.Equal(t, token.Value, extendedToken.Value)
  526. require.Equal(t, "changed label", extendedToken.Label)
  527. require.True(t, token.Expires.Unix() < extendedToken.Expires.Unix())
  528. require.True(t, time.Now().Add(99*time.Hour).Unix() < extendedToken.Expires.Unix())
  529. }
  530. func TestManager_Token_MaxCount_AutoDelete(t *testing.T) {
  531. // Tests that tokens are automatically deleted when the maximum number of tokens is reached
  532. a := newTestManager(t, PermissionDenyAll)
  533. require.Nil(t, a.AddUser("ben", "ben", RoleUser))
  534. require.Nil(t, a.AddUser("phil", "phil", RoleUser))
  535. ben, err := a.User("ben")
  536. require.Nil(t, err)
  537. phil, err := a.User("phil")
  538. require.Nil(t, err)
  539. // Create 2 tokens for phil
  540. philTokens := make([]string, 0)
  541. token, err := a.CreateToken(phil.ID, "", time.Now().Add(72*time.Hour), netip.IPv4Unspecified())
  542. require.Nil(t, err)
  543. require.NotEmpty(t, token.Value)
  544. philTokens = append(philTokens, token.Value)
  545. token, err = a.CreateToken(phil.ID, "", time.Unix(0, 0), netip.IPv4Unspecified())
  546. require.Nil(t, err)
  547. require.NotEmpty(t, token.Value)
  548. philTokens = append(philTokens, token.Value)
  549. // Create 22 tokens for ben (only 20 allowed!)
  550. baseTime := time.Now().Add(24 * time.Hour)
  551. benTokens := make([]string, 0)
  552. for i := 0; i < 22; i++ { //
  553. token, err := a.CreateToken(ben.ID, "", time.Now().Add(72*time.Hour), netip.IPv4Unspecified())
  554. require.Nil(t, err)
  555. require.NotEmpty(t, token.Value)
  556. benTokens = append(benTokens, token.Value)
  557. // Manually modify expiry date to avoid sorting issues (this is a hack)
  558. _, err = a.db.Exec(`UPDATE user_token SET expires=? WHERE token=?`, baseTime.Add(time.Duration(i)*time.Minute).Unix(), token.Value)
  559. require.Nil(t, err)
  560. }
  561. // Ben: The first 2 tokens should have been wiped and should not work anymore!
  562. _, err = a.AuthenticateToken(benTokens[0])
  563. require.Equal(t, ErrUnauthenticated, err)
  564. _, err = a.AuthenticateToken(benTokens[1])
  565. require.Equal(t, ErrUnauthenticated, err)
  566. // Ben: The other tokens should still work
  567. for i := 2; i < 22; i++ {
  568. userWithToken, err := a.AuthenticateToken(benTokens[i])
  569. require.Nil(t, err, "token[%d]=%s failed", i, benTokens[i])
  570. require.Equal(t, "ben", userWithToken.Name)
  571. require.Equal(t, benTokens[i], userWithToken.Token)
  572. }
  573. // Phil: All tokens should still work
  574. for i := 0; i < 2; i++ {
  575. userWithToken, err := a.AuthenticateToken(philTokens[i])
  576. require.Nil(t, err, "token[%d]=%s failed", i, philTokens[i])
  577. require.Equal(t, "phil", userWithToken.Name)
  578. require.Equal(t, philTokens[i], userWithToken.Token)
  579. }
  580. var benCount int
  581. rows, err := a.db.Query(`SELECT COUNT(*) FROM user_token WHERE user_id=?`, ben.ID)
  582. require.Nil(t, err)
  583. require.True(t, rows.Next())
  584. require.Nil(t, rows.Scan(&benCount))
  585. require.Equal(t, 20, benCount)
  586. var philCount int
  587. rows, err = a.db.Query(`SELECT COUNT(*) FROM user_token WHERE user_id=?`, phil.ID)
  588. require.Nil(t, err)
  589. require.True(t, rows.Next())
  590. require.Nil(t, rows.Scan(&philCount))
  591. require.Equal(t, 2, philCount)
  592. }
  593. func TestManager_EnqueueStats_ResetStats(t *testing.T) {
  594. a, err := NewManager(filepath.Join(t.TempDir(), "db"), "", PermissionReadWrite, bcrypt.MinCost, 1500*time.Millisecond)
  595. require.Nil(t, err)
  596. require.Nil(t, a.AddUser("ben", "ben", RoleUser))
  597. // Baseline: No messages or emails
  598. u, err := a.User("ben")
  599. require.Nil(t, err)
  600. require.Equal(t, int64(0), u.Stats.Messages)
  601. require.Equal(t, int64(0), u.Stats.Emails)
  602. a.EnqueueUserStats(u.ID, &Stats{
  603. Messages: 11,
  604. Emails: 2,
  605. })
  606. // Still no change, because it's queued asynchronously
  607. u, err = a.User("ben")
  608. require.Nil(t, err)
  609. require.Equal(t, int64(0), u.Stats.Messages)
  610. require.Equal(t, int64(0), u.Stats.Emails)
  611. // After 2 seconds they should be persisted
  612. time.Sleep(2 * time.Second)
  613. u, err = a.User("ben")
  614. require.Nil(t, err)
  615. require.Equal(t, int64(11), u.Stats.Messages)
  616. require.Equal(t, int64(2), u.Stats.Emails)
  617. // Now reset stats (enqueued stats will be thrown out)
  618. a.EnqueueUserStats(u.ID, &Stats{
  619. Messages: 99,
  620. Emails: 23,
  621. })
  622. require.Nil(t, a.ResetStats())
  623. u, err = a.User("ben")
  624. require.Nil(t, err)
  625. require.Equal(t, int64(0), u.Stats.Messages)
  626. require.Equal(t, int64(0), u.Stats.Emails)
  627. }
  628. func TestManager_EnqueueTokenUpdate(t *testing.T) {
  629. a, err := NewManager(filepath.Join(t.TempDir(), "db"), "", PermissionReadWrite, bcrypt.MinCost, 500*time.Millisecond)
  630. require.Nil(t, err)
  631. require.Nil(t, a.AddUser("ben", "ben", RoleUser))
  632. // Create user and token
  633. u, err := a.User("ben")
  634. require.Nil(t, err)
  635. token, err := a.CreateToken(u.ID, "", time.Now().Add(time.Hour), netip.IPv4Unspecified())
  636. require.Nil(t, err)
  637. // Queue token update
  638. a.EnqueueTokenUpdate(token.Value, &TokenUpdate{
  639. LastAccess: time.Unix(111, 0).UTC(),
  640. LastOrigin: netip.MustParseAddr("1.2.3.3"),
  641. })
  642. // Token has not changed yet.
  643. token2, err := a.Token(u.ID, token.Value)
  644. require.Nil(t, err)
  645. require.Equal(t, token.LastAccess.Unix(), token2.LastAccess.Unix())
  646. require.Equal(t, token.LastOrigin, token2.LastOrigin)
  647. // After a second or so they should be persisted
  648. time.Sleep(time.Second)
  649. token3, err := a.Token(u.ID, token.Value)
  650. require.Nil(t, err)
  651. require.Equal(t, time.Unix(111, 0).UTC().Unix(), token3.LastAccess.Unix())
  652. require.Equal(t, netip.MustParseAddr("1.2.3.3"), token3.LastOrigin)
  653. }
  654. func TestManager_ChangeSettings(t *testing.T) {
  655. a, err := NewManager(filepath.Join(t.TempDir(), "db"), "", PermissionReadWrite, bcrypt.MinCost, 1500*time.Millisecond)
  656. require.Nil(t, err)
  657. require.Nil(t, a.AddUser("ben", "ben", RoleUser))
  658. // No settings
  659. u, err := a.User("ben")
  660. require.Nil(t, err)
  661. require.Nil(t, u.Prefs.Subscriptions)
  662. require.Nil(t, u.Prefs.Notification)
  663. require.Nil(t, u.Prefs.Language)
  664. // Save with new settings
  665. prefs := &Prefs{
  666. Language: util.String("de"),
  667. Notification: &NotificationPrefs{
  668. Sound: util.String("ding"),
  669. MinPriority: util.Int(2),
  670. },
  671. Subscriptions: []*Subscription{
  672. {
  673. BaseURL: "https://ntfy.sh",
  674. Topic: "mytopic",
  675. DisplayName: util.String("My Topic"),
  676. },
  677. },
  678. }
  679. require.Nil(t, a.ChangeSettings(u.ID, prefs))
  680. // Read again
  681. u, err = a.User("ben")
  682. require.Nil(t, err)
  683. require.Equal(t, util.String("de"), u.Prefs.Language)
  684. require.Equal(t, util.String("ding"), u.Prefs.Notification.Sound)
  685. require.Equal(t, util.Int(2), u.Prefs.Notification.MinPriority)
  686. require.Nil(t, u.Prefs.Notification.DeleteAfter)
  687. require.Equal(t, "https://ntfy.sh", u.Prefs.Subscriptions[0].BaseURL)
  688. require.Equal(t, "mytopic", u.Prefs.Subscriptions[0].Topic)
  689. require.Equal(t, util.String("My Topic"), u.Prefs.Subscriptions[0].DisplayName)
  690. }
  691. func TestManager_Tier_Create_Update_List_Delete(t *testing.T) {
  692. a := newTestManager(t, PermissionDenyAll)
  693. // Create tier and user
  694. require.Nil(t, a.AddTier(&Tier{
  695. Code: "supporter",
  696. Name: "Supporter",
  697. MessageLimit: 1,
  698. MessageExpiryDuration: time.Second,
  699. EmailLimit: 1,
  700. ReservationLimit: 1,
  701. AttachmentFileSizeLimit: 1,
  702. AttachmentTotalSizeLimit: 1,
  703. AttachmentExpiryDuration: time.Second,
  704. AttachmentBandwidthLimit: 1,
  705. StripeMonthlyPriceID: "price_1",
  706. }))
  707. require.Nil(t, a.AddTier(&Tier{
  708. Code: "pro",
  709. Name: "Pro",
  710. MessageLimit: 123,
  711. MessageExpiryDuration: 86400 * time.Second,
  712. EmailLimit: 32,
  713. ReservationLimit: 2,
  714. AttachmentFileSizeLimit: 1231231,
  715. AttachmentTotalSizeLimit: 123123,
  716. AttachmentExpiryDuration: 10800 * time.Second,
  717. AttachmentBandwidthLimit: 21474836480,
  718. StripeMonthlyPriceID: "price_2",
  719. }))
  720. require.Nil(t, a.AddUser("phil", "phil", RoleUser))
  721. require.Nil(t, a.ChangeTier("phil", "pro"))
  722. ti, err := a.Tier("pro")
  723. require.Nil(t, err)
  724. u, err := a.User("phil")
  725. require.Nil(t, err)
  726. // These are populated by different SQL queries
  727. require.Equal(t, ti, u.Tier)
  728. // Fields
  729. require.True(t, strings.HasPrefix(ti.ID, "ti_"))
  730. require.Equal(t, "pro", ti.Code)
  731. require.Equal(t, "Pro", ti.Name)
  732. require.Equal(t, int64(123), ti.MessageLimit)
  733. require.Equal(t, 86400*time.Second, ti.MessageExpiryDuration)
  734. require.Equal(t, int64(32), ti.EmailLimit)
  735. require.Equal(t, int64(2), ti.ReservationLimit)
  736. require.Equal(t, int64(1231231), ti.AttachmentFileSizeLimit)
  737. require.Equal(t, int64(123123), ti.AttachmentTotalSizeLimit)
  738. require.Equal(t, 10800*time.Second, ti.AttachmentExpiryDuration)
  739. require.Equal(t, int64(21474836480), ti.AttachmentBandwidthLimit)
  740. require.Equal(t, "price_2", ti.StripeMonthlyPriceID)
  741. // Update tier
  742. ti.EmailLimit = 999999
  743. require.Nil(t, a.UpdateTier(ti))
  744. // List tiers
  745. tiers, err := a.Tiers()
  746. require.Nil(t, err)
  747. require.Equal(t, 2, len(tiers))
  748. ti = tiers[0]
  749. require.Equal(t, "supporter", ti.Code)
  750. require.Equal(t, "Supporter", ti.Name)
  751. require.Equal(t, int64(1), ti.MessageLimit)
  752. require.Equal(t, time.Second, ti.MessageExpiryDuration)
  753. require.Equal(t, int64(1), ti.EmailLimit)
  754. require.Equal(t, int64(1), ti.ReservationLimit)
  755. require.Equal(t, int64(1), ti.AttachmentFileSizeLimit)
  756. require.Equal(t, int64(1), ti.AttachmentTotalSizeLimit)
  757. require.Equal(t, time.Second, ti.AttachmentExpiryDuration)
  758. require.Equal(t, int64(1), ti.AttachmentBandwidthLimit)
  759. require.Equal(t, "price_1", ti.StripeMonthlyPriceID)
  760. ti = tiers[1]
  761. require.Equal(t, "pro", ti.Code)
  762. require.Equal(t, "Pro", ti.Name)
  763. require.Equal(t, int64(123), ti.MessageLimit)
  764. require.Equal(t, 86400*time.Second, ti.MessageExpiryDuration)
  765. require.Equal(t, int64(999999), ti.EmailLimit) // Updatedd!
  766. require.Equal(t, int64(2), ti.ReservationLimit)
  767. require.Equal(t, int64(1231231), ti.AttachmentFileSizeLimit)
  768. require.Equal(t, int64(123123), ti.AttachmentTotalSizeLimit)
  769. require.Equal(t, 10800*time.Second, ti.AttachmentExpiryDuration)
  770. require.Equal(t, int64(21474836480), ti.AttachmentBandwidthLimit)
  771. require.Equal(t, "price_2", ti.StripeMonthlyPriceID)
  772. ti, err = a.TierByStripePrice("price_1")
  773. require.Nil(t, err)
  774. require.Equal(t, "supporter", ti.Code)
  775. require.Equal(t, "Supporter", ti.Name)
  776. require.Equal(t, int64(1), ti.MessageLimit)
  777. require.Equal(t, time.Second, ti.MessageExpiryDuration)
  778. require.Equal(t, int64(1), ti.EmailLimit)
  779. require.Equal(t, int64(1), ti.ReservationLimit)
  780. require.Equal(t, int64(1), ti.AttachmentFileSizeLimit)
  781. require.Equal(t, int64(1), ti.AttachmentTotalSizeLimit)
  782. require.Equal(t, time.Second, ti.AttachmentExpiryDuration)
  783. require.Equal(t, int64(1), ti.AttachmentBandwidthLimit)
  784. require.Equal(t, "price_1", ti.StripeMonthlyPriceID)
  785. // Cannot remove tier, since user has this tier
  786. require.Error(t, a.RemoveTier("pro"))
  787. // CAN remove this tier
  788. require.Nil(t, a.RemoveTier("supporter"))
  789. tiers, err = a.Tiers()
  790. require.Nil(t, err)
  791. require.Equal(t, 1, len(tiers))
  792. require.Equal(t, "pro", tiers[0].Code)
  793. require.Equal(t, "pro", tiers[0].Code)
  794. }
  795. func TestAccount_Tier_Create_With_ID(t *testing.T) {
  796. a := newTestManager(t, PermissionDenyAll)
  797. require.Nil(t, a.AddTier(&Tier{
  798. ID: "ti_123",
  799. Code: "pro",
  800. }))
  801. ti, err := a.Tier("pro")
  802. require.Nil(t, err)
  803. require.Equal(t, "ti_123", ti.ID)
  804. }
  805. func TestManager_Tier_Change_And_Reset(t *testing.T) {
  806. a := newTestManager(t, PermissionDenyAll)
  807. // Create tier and user
  808. require.Nil(t, a.AddTier(&Tier{
  809. Code: "supporter",
  810. Name: "Supporter",
  811. ReservationLimit: 3,
  812. }))
  813. require.Nil(t, a.AddTier(&Tier{
  814. Code: "pro",
  815. Name: "Pro",
  816. ReservationLimit: 4,
  817. }))
  818. require.Nil(t, a.AddUser("phil", "phil", RoleUser))
  819. require.Nil(t, a.ChangeTier("phil", "pro"))
  820. // Add 10 reservations (pro tier allows that)
  821. for i := 0; i < 4; i++ {
  822. require.Nil(t, a.AddReservation("phil", fmt.Sprintf("topic%d", i), PermissionWrite))
  823. }
  824. // Downgrading will not work (too many reservations)
  825. require.Equal(t, ErrTooManyReservations, a.ChangeTier("phil", "supporter"))
  826. // Downgrade after removing a reservation
  827. require.Nil(t, a.RemoveReservations("phil", "topic0"))
  828. require.Nil(t, a.ChangeTier("phil", "supporter"))
  829. // Resetting will not work (too many reservations)
  830. require.Equal(t, ErrTooManyReservations, a.ResetTier("phil"))
  831. // Resetting after removing all reservations
  832. require.Nil(t, a.RemoveReservations("phil", "topic1", "topic2", "topic3"))
  833. require.Nil(t, a.ResetTier("phil"))
  834. }
  835. func TestUser_PhoneNumberAddListRemove(t *testing.T) {
  836. a := newTestManager(t, PermissionDenyAll)
  837. require.Nil(t, a.AddUser("phil", "phil", RoleUser))
  838. phil, err := a.User("phil")
  839. require.Nil(t, err)
  840. require.Nil(t, a.AddPhoneNumber(phil.ID, "+1234567890"))
  841. phoneNumbers, err := a.PhoneNumbers(phil.ID)
  842. require.Nil(t, err)
  843. require.Equal(t, 1, len(phoneNumbers))
  844. require.Equal(t, "+1234567890", phoneNumbers[0])
  845. require.Nil(t, a.RemovePhoneNumber(phil.ID, "+1234567890"))
  846. phoneNumbers, err = a.PhoneNumbers(phil.ID)
  847. require.Nil(t, err)
  848. require.Equal(t, 0, len(phoneNumbers))
  849. // Paranoia check: We do NOT want to keep phone numbers in there
  850. rows, err := a.db.Query(`SELECT * FROM user_phone`)
  851. require.Nil(t, err)
  852. require.False(t, rows.Next())
  853. require.Nil(t, rows.Close())
  854. }
  855. func TestUser_PhoneNumberAdd_Multiple_Users_Same_Number(t *testing.T) {
  856. a := newTestManager(t, PermissionDenyAll)
  857. require.Nil(t, a.AddUser("phil", "phil", RoleUser))
  858. require.Nil(t, a.AddUser("ben", "ben", RoleUser))
  859. phil, err := a.User("phil")
  860. require.Nil(t, err)
  861. ben, err := a.User("ben")
  862. require.Nil(t, err)
  863. require.Nil(t, a.AddPhoneNumber(phil.ID, "+1234567890"))
  864. require.Nil(t, a.AddPhoneNumber(ben.ID, "+1234567890"))
  865. }
  866. func TestManager_Topic_Wildcard_With_Asterisk_Underscore(t *testing.T) {
  867. f := filepath.Join(t.TempDir(), "user.db")
  868. a := newTestManagerFromFile(t, f, "", PermissionDenyAll, DefaultUserPasswordBcryptCost, DefaultUserStatsQueueWriterInterval)
  869. require.Nil(t, a.AllowAccess(Everyone, "*_", PermissionRead))
  870. require.Nil(t, a.AllowAccess(Everyone, "__*_", PermissionRead))
  871. require.Nil(t, a.Authorize(nil, "allowed_", PermissionRead))
  872. require.Nil(t, a.Authorize(nil, "__allowed_", PermissionRead))
  873. require.Nil(t, a.Authorize(nil, "_allowed_", PermissionRead)) // The "%" in "%\_" matches the first "_"
  874. require.Equal(t, ErrUnauthorized, a.Authorize(nil, "notallowed", PermissionRead))
  875. require.Equal(t, ErrUnauthorized, a.Authorize(nil, "_notallowed", PermissionRead))
  876. require.Equal(t, ErrUnauthorized, a.Authorize(nil, "__notallowed", PermissionRead))
  877. }
  878. func TestManager_Topic_Wildcard_With_Underscore(t *testing.T) {
  879. f := filepath.Join(t.TempDir(), "user.db")
  880. a := newTestManagerFromFile(t, f, "", PermissionDenyAll, DefaultUserPasswordBcryptCost, DefaultUserStatsQueueWriterInterval)
  881. require.Nil(t, a.AllowAccess(Everyone, "mytopic_", PermissionReadWrite))
  882. require.Nil(t, a.Authorize(nil, "mytopic_", PermissionRead))
  883. require.Nil(t, a.Authorize(nil, "mytopic_", PermissionWrite))
  884. require.Equal(t, ErrUnauthorized, a.Authorize(nil, "mytopicX", PermissionRead))
  885. require.Equal(t, ErrUnauthorized, a.Authorize(nil, "mytopicX", PermissionWrite))
  886. }
  887. func TestToFromSQLWildcard(t *testing.T) {
  888. require.Equal(t, "up%", toSQLWildcard("up*"))
  889. require.Equal(t, "up\\_%", toSQLWildcard("up_*"))
  890. require.Equal(t, "foo", toSQLWildcard("foo"))
  891. require.Equal(t, "up*", fromSQLWildcard("up%"))
  892. require.Equal(t, "up_*", fromSQLWildcard("up\\_%"))
  893. require.Equal(t, "foo", fromSQLWildcard("foo"))
  894. require.Equal(t, "up*", fromSQLWildcard(toSQLWildcard("up*")))
  895. require.Equal(t, "up_*", fromSQLWildcard(toSQLWildcard("up_*")))
  896. require.Equal(t, "foo", fromSQLWildcard(toSQLWildcard("foo")))
  897. }
  898. func TestMigrationFrom1(t *testing.T) {
  899. filename := filepath.Join(t.TempDir(), "user.db")
  900. db, err := sql.Open("sqlite3", filename)
  901. require.Nil(t, err)
  902. // Create "version 1" schema
  903. _, err = db.Exec(`
  904. BEGIN;
  905. CREATE TABLE IF NOT EXISTS user (
  906. user TEXT NOT NULL PRIMARY KEY,
  907. pass TEXT NOT NULL,
  908. role TEXT NOT NULL
  909. );
  910. CREATE TABLE IF NOT EXISTS access (
  911. user TEXT NOT NULL,
  912. topic TEXT NOT NULL,
  913. read INT NOT NULL,
  914. write INT NOT NULL,
  915. PRIMARY KEY (topic, user)
  916. );
  917. CREATE TABLE IF NOT EXISTS schemaVersion (
  918. id INT PRIMARY KEY,
  919. version INT NOT NULL
  920. );
  921. INSERT INTO schemaVersion (id, version) VALUES (1, 1);
  922. COMMIT;
  923. `)
  924. require.Nil(t, err)
  925. // Insert a bunch of users and ACL entries
  926. _, err = db.Exec(`
  927. BEGIN;
  928. INSERT INTO user (user, pass, role) VALUES ('ben', '$2a$10$EEp6gBheOsqEFsXlo523E.gBVoeg1ytphXiEvTPlNzkenBlHZBPQy', 'user');
  929. INSERT INTO user (user, pass, role) VALUES ('phil', '$2a$10$YLiO8U21sX1uhZamTLJXHuxgVC0Z/GKISibrKCLohPgtG7yIxSk4C', 'admin');
  930. INSERT INTO access (user, topic, read, write) VALUES ('ben', 'stats', 1, 1);
  931. INSERT INTO access (user, topic, read, write) VALUES ('ben', 'secret', 1, 0);
  932. INSERT INTO access (user, topic, read, write) VALUES ('*', 'stats', 1, 0);
  933. COMMIT;
  934. `)
  935. require.Nil(t, err)
  936. // Create manager to trigger migration
  937. a := newTestManagerFromFile(t, filename, "", PermissionDenyAll, bcrypt.MinCost, DefaultUserStatsQueueWriterInterval)
  938. checkSchemaVersion(t, a.db)
  939. users, err := a.Users()
  940. require.Nil(t, err)
  941. require.Equal(t, 3, len(users))
  942. phil, ben, everyone := users[0], users[1], users[2]
  943. philGrants, err := a.Grants("phil")
  944. require.Nil(t, err)
  945. benGrants, err := a.Grants("ben")
  946. require.Nil(t, err)
  947. everyoneGrants, err := a.Grants(Everyone)
  948. require.Nil(t, err)
  949. require.True(t, strings.HasPrefix(phil.ID, "u_"))
  950. require.Equal(t, "phil", phil.Name)
  951. require.Equal(t, RoleAdmin, phil.Role)
  952. require.Equal(t, syncTopicLength, len(phil.SyncTopic))
  953. require.Equal(t, 0, len(philGrants))
  954. require.True(t, strings.HasPrefix(ben.ID, "u_"))
  955. require.NotEqual(t, phil.ID, ben.ID)
  956. require.Equal(t, "ben", ben.Name)
  957. require.Equal(t, RoleUser, ben.Role)
  958. require.Equal(t, syncTopicLength, len(ben.SyncTopic))
  959. require.NotEqual(t, ben.SyncTopic, phil.SyncTopic)
  960. require.Equal(t, 2, len(benGrants))
  961. require.Equal(t, "secret", benGrants[0].TopicPattern)
  962. require.Equal(t, PermissionRead, benGrants[0].Allow)
  963. require.Equal(t, "stats", benGrants[1].TopicPattern)
  964. require.Equal(t, PermissionReadWrite, benGrants[1].Allow)
  965. require.Equal(t, "u_everyone", everyone.ID)
  966. require.Equal(t, Everyone, everyone.Name)
  967. require.Equal(t, RoleAnonymous, everyone.Role)
  968. require.Equal(t, 1, len(everyoneGrants))
  969. require.Equal(t, "stats", everyoneGrants[0].TopicPattern)
  970. require.Equal(t, PermissionRead, everyoneGrants[0].Allow)
  971. }
  972. func TestMigrationFrom4(t *testing.T) {
  973. filename := filepath.Join(t.TempDir(), "user.db")
  974. db, err := sql.Open("sqlite3", filename)
  975. require.Nil(t, err)
  976. // Create "version 4" schema
  977. _, err = db.Exec(`
  978. BEGIN;
  979. CREATE TABLE IF NOT EXISTS tier (
  980. id TEXT PRIMARY KEY,
  981. code TEXT NOT NULL,
  982. name TEXT NOT NULL,
  983. messages_limit INT NOT NULL,
  984. messages_expiry_duration INT NOT NULL,
  985. emails_limit INT NOT NULL,
  986. calls_limit INT NOT NULL,
  987. reservations_limit INT NOT NULL,
  988. attachment_file_size_limit INT NOT NULL,
  989. attachment_total_size_limit INT NOT NULL,
  990. attachment_expiry_duration INT NOT NULL,
  991. attachment_bandwidth_limit INT NOT NULL,
  992. stripe_monthly_price_id TEXT,
  993. stripe_yearly_price_id TEXT
  994. );
  995. CREATE UNIQUE INDEX idx_tier_code ON tier (code);
  996. CREATE UNIQUE INDEX idx_tier_stripe_monthly_price_id ON tier (stripe_monthly_price_id);
  997. CREATE UNIQUE INDEX idx_tier_stripe_yearly_price_id ON tier (stripe_yearly_price_id);
  998. CREATE TABLE IF NOT EXISTS user (
  999. id TEXT PRIMARY KEY,
  1000. tier_id TEXT,
  1001. user TEXT NOT NULL,
  1002. pass TEXT NOT NULL,
  1003. role TEXT CHECK (role IN ('anonymous', 'admin', 'user')) NOT NULL,
  1004. prefs JSON NOT NULL DEFAULT '{}',
  1005. sync_topic TEXT NOT NULL,
  1006. stats_messages INT NOT NULL DEFAULT (0),
  1007. stats_emails INT NOT NULL DEFAULT (0),
  1008. stats_calls INT NOT NULL DEFAULT (0),
  1009. stripe_customer_id TEXT,
  1010. stripe_subscription_id TEXT,
  1011. stripe_subscription_status TEXT,
  1012. stripe_subscription_interval TEXT,
  1013. stripe_subscription_paid_until INT,
  1014. stripe_subscription_cancel_at INT,
  1015. created INT NOT NULL,
  1016. deleted INT,
  1017. FOREIGN KEY (tier_id) REFERENCES tier (id)
  1018. );
  1019. CREATE UNIQUE INDEX idx_user ON user (user);
  1020. CREATE UNIQUE INDEX idx_user_stripe_customer_id ON user (stripe_customer_id);
  1021. CREATE UNIQUE INDEX idx_user_stripe_subscription_id ON user (stripe_subscription_id);
  1022. CREATE TABLE IF NOT EXISTS user_access (
  1023. user_id TEXT NOT NULL,
  1024. topic TEXT NOT NULL,
  1025. read INT NOT NULL,
  1026. write INT NOT NULL,
  1027. owner_user_id INT,
  1028. PRIMARY KEY (user_id, topic),
  1029. FOREIGN KEY (user_id) REFERENCES user (id) ON DELETE CASCADE,
  1030. FOREIGN KEY (owner_user_id) REFERENCES user (id) ON DELETE CASCADE
  1031. );
  1032. CREATE TABLE IF NOT EXISTS user_token (
  1033. user_id TEXT NOT NULL,
  1034. token TEXT NOT NULL,
  1035. label TEXT NOT NULL,
  1036. last_access INT NOT NULL,
  1037. last_origin TEXT NOT NULL,
  1038. expires INT NOT NULL,
  1039. PRIMARY KEY (user_id, token),
  1040. FOREIGN KEY (user_id) REFERENCES user (id) ON DELETE CASCADE
  1041. );
  1042. CREATE TABLE IF NOT EXISTS user_phone (
  1043. user_id TEXT NOT NULL,
  1044. phone_number TEXT NOT NULL,
  1045. PRIMARY KEY (user_id, phone_number),
  1046. FOREIGN KEY (user_id) REFERENCES user (id) ON DELETE CASCADE
  1047. );
  1048. CREATE TABLE IF NOT EXISTS schemaVersion (
  1049. id INT PRIMARY KEY,
  1050. version INT NOT NULL
  1051. );
  1052. INSERT INTO user (id, user, pass, role, sync_topic, created)
  1053. VALUES ('u_everyone', '*', '', 'anonymous', '', UNIXEPOCH())
  1054. ON CONFLICT (id) DO NOTHING;
  1055. INSERT INTO schemaVersion (id, version) VALUES (1, 4);
  1056. COMMIT;
  1057. `)
  1058. require.Nil(t, err)
  1059. // Insert a few ACL entries
  1060. _, err = db.Exec(`
  1061. BEGIN;
  1062. INSERT INTO user_access (user_id, topic, read, write) values ('u_everyone', 'mytopic_', 1, 1);
  1063. INSERT INTO user_access (user_id, topic, read, write) values ('u_everyone', 'up%', 1, 1);
  1064. INSERT INTO user_access (user_id, topic, read, write) values ('u_everyone', 'down_%', 1, 1);
  1065. COMMIT;
  1066. `)
  1067. require.Nil(t, err)
  1068. // Create manager to trigger migration
  1069. a := newTestManagerFromFile(t, filename, "", PermissionDenyAll, bcrypt.MinCost, DefaultUserStatsQueueWriterInterval)
  1070. checkSchemaVersion(t, a.db)
  1071. // Add another
  1072. require.Nil(t, a.AllowAccess(Everyone, "left_*", PermissionReadWrite))
  1073. // Check "external view" of grants
  1074. everyoneGrants, err := a.Grants(Everyone)
  1075. require.Nil(t, err)
  1076. require.Equal(t, 4, len(everyoneGrants))
  1077. require.Equal(t, "mytopic_", everyoneGrants[0].TopicPattern)
  1078. require.Equal(t, "down_*", everyoneGrants[1].TopicPattern)
  1079. require.Equal(t, "left_*", everyoneGrants[2].TopicPattern)
  1080. require.Equal(t, "up*", everyoneGrants[3].TopicPattern)
  1081. // Check they are stored correctly in the database
  1082. rows, err := db.Query(`SELECT topic FROM user_access WHERE user_id = 'u_everyone' ORDER BY topic`)
  1083. require.Nil(t, err)
  1084. topicPatterns := make([]string, 0)
  1085. for rows.Next() {
  1086. var topicPattern string
  1087. require.Nil(t, rows.Scan(&topicPattern))
  1088. topicPatterns = append(topicPatterns, topicPattern)
  1089. }
  1090. require.Nil(t, rows.Close())
  1091. require.Equal(t, 4, len(topicPatterns))
  1092. require.Equal(t, "down\\_%", topicPatterns[0])
  1093. require.Equal(t, "left\\_%", topicPatterns[1])
  1094. require.Equal(t, "mytopic\\_", topicPatterns[2])
  1095. require.Equal(t, "up%", topicPatterns[3])
  1096. // Check that ACL works as excepted
  1097. require.Nil(t, a.Authorize(nil, "down_123", PermissionRead))
  1098. require.Equal(t, ErrUnauthorized, a.Authorize(nil, "downX123", PermissionRead))
  1099. require.Nil(t, a.Authorize(nil, "left_abc", PermissionRead))
  1100. require.Equal(t, ErrUnauthorized, a.Authorize(nil, "leftX123", PermissionRead))
  1101. require.Nil(t, a.Authorize(nil, "mytopic_", PermissionRead))
  1102. require.Equal(t, ErrUnauthorized, a.Authorize(nil, "mytopicX", PermissionRead))
  1103. require.Nil(t, a.Authorize(nil, "up123", PermissionRead))
  1104. require.Nil(t, a.Authorize(nil, "up", PermissionRead)) // % matches 0 or more characters
  1105. }
  1106. func checkSchemaVersion(t *testing.T, db *sql.DB) {
  1107. rows, err := db.Query(`SELECT version FROM schemaVersion`)
  1108. require.Nil(t, err)
  1109. require.True(t, rows.Next())
  1110. var schemaVersion int
  1111. require.Nil(t, rows.Scan(&schemaVersion))
  1112. require.Equal(t, currentSchemaVersion, schemaVersion)
  1113. require.Nil(t, rows.Close())
  1114. }
  1115. func newTestManager(t *testing.T, defaultAccess Permission) *Manager {
  1116. return newTestManagerFromFile(t, filepath.Join(t.TempDir(), "user.db"), "", defaultAccess, bcrypt.MinCost, DefaultUserStatsQueueWriterInterval)
  1117. }
  1118. func newTestManagerFromFile(t *testing.T, filename, startupQueries string, defaultAccess Permission, bcryptCost int, statsWriterInterval time.Duration) *Manager {
  1119. a, err := NewManager(filename, startupQueries, defaultAccess, bcryptCost, statsWriterInterval)
  1120. require.Nil(t, err)
  1121. return a
  1122. }