manager_test.go 44 KB

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