server_account_test.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  1. package server
  2. import (
  3. "fmt"
  4. "github.com/stretchr/testify/require"
  5. "heckel.io/ntfy/log"
  6. "heckel.io/ntfy/user"
  7. "heckel.io/ntfy/util"
  8. "io"
  9. "net/netip"
  10. "path/filepath"
  11. "strings"
  12. "testing"
  13. "time"
  14. )
  15. func TestAccount_Signup_Success(t *testing.T) {
  16. conf := newTestConfigWithAuthFile(t)
  17. conf.EnableSignup = true
  18. s := newTestServer(t, conf)
  19. defer s.closeDatabases()
  20. rr := request(t, s, "POST", "/v1/account", `{"username":"phil", "password":"mypass"}`, nil)
  21. require.Equal(t, 200, rr.Code)
  22. rr = request(t, s, "POST", "/v1/account/token", "", map[string]string{
  23. "Authorization": util.BasicAuth("phil", "mypass"),
  24. })
  25. require.Equal(t, 200, rr.Code)
  26. token, _ := util.UnmarshalJSON[apiAccountTokenResponse](io.NopCloser(rr.Body))
  27. require.NotEmpty(t, token.Token)
  28. require.True(t, time.Now().Add(71*time.Hour).Unix() < token.Expires)
  29. require.True(t, strings.HasPrefix(token.Token, "tk_"))
  30. require.Equal(t, "9.9.9.9", token.LastOrigin)
  31. require.True(t, token.LastAccess > time.Now().Unix()-2)
  32. require.True(t, token.LastAccess < time.Now().Unix()+2)
  33. rr = request(t, s, "GET", "/v1/account", "", map[string]string{
  34. "Authorization": util.BearerAuth(token.Token),
  35. })
  36. require.Equal(t, 200, rr.Code)
  37. account, _ := util.UnmarshalJSON[apiAccountResponse](io.NopCloser(rr.Body))
  38. require.Equal(t, "phil", account.Username)
  39. require.Equal(t, "user", account.Role)
  40. rr = request(t, s, "GET", "/v1/account", "", map[string]string{
  41. "Authorization": util.BasicAuth("", token.Token), // We allow a fake basic auth to make curl-ing easier (curl -u :<token>)
  42. })
  43. require.Equal(t, 200, rr.Code)
  44. account, _ = util.UnmarshalJSON[apiAccountResponse](io.NopCloser(rr.Body))
  45. require.Equal(t, "phil", account.Username)
  46. }
  47. func TestAccount_Signup_UserExists(t *testing.T) {
  48. conf := newTestConfigWithAuthFile(t)
  49. conf.EnableSignup = true
  50. s := newTestServer(t, conf)
  51. defer s.closeDatabases()
  52. rr := request(t, s, "POST", "/v1/account", `{"username":"phil", "password":"mypass"}`, nil)
  53. require.Equal(t, 200, rr.Code)
  54. rr = request(t, s, "POST", "/v1/account", `{"username":"phil", "password":"mypass"}`, nil)
  55. require.Equal(t, 409, rr.Code)
  56. require.Equal(t, 40901, toHTTPError(t, rr.Body.String()).Code)
  57. }
  58. func TestAccount_Signup_LimitReached(t *testing.T) {
  59. conf := newTestConfigWithAuthFile(t)
  60. conf.EnableSignup = true
  61. s := newTestServer(t, conf)
  62. defer s.closeDatabases()
  63. for i := 0; i < 3; i++ {
  64. rr := request(t, s, "POST", "/v1/account", fmt.Sprintf(`{"username":"phil%d", "password":"mypass"}`, i), nil)
  65. require.Equal(t, 200, rr.Code)
  66. }
  67. rr := request(t, s, "POST", "/v1/account", `{"username":"thiswontwork", "password":"mypass"}`, nil)
  68. require.Equal(t, 429, rr.Code)
  69. require.Equal(t, 42906, toHTTPError(t, rr.Body.String()).Code)
  70. }
  71. func TestAccount_Signup_AsUser(t *testing.T) {
  72. conf := newTestConfigWithAuthFile(t)
  73. conf.EnableSignup = true
  74. s := newTestServer(t, conf)
  75. defer s.closeDatabases()
  76. log.Info("1")
  77. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleAdmin))
  78. log.Info("2")
  79. require.Nil(t, s.userManager.AddUser("ben", "ben", user.RoleUser))
  80. log.Info("3")
  81. rr := request(t, s, "POST", "/v1/account", `{"username":"emma", "password":"emma"}`, map[string]string{
  82. "Authorization": util.BasicAuth("phil", "phil"),
  83. })
  84. require.Equal(t, 200, rr.Code)
  85. log.Info("4")
  86. rr = request(t, s, "POST", "/v1/account", `{"username":"marian", "password":"marian"}`, map[string]string{
  87. "Authorization": util.BasicAuth("ben", "ben"),
  88. })
  89. require.Equal(t, 401, rr.Code)
  90. }
  91. func TestAccount_Signup_Disabled(t *testing.T) {
  92. conf := newTestConfigWithAuthFile(t)
  93. conf.EnableSignup = false
  94. s := newTestServer(t, conf)
  95. defer s.closeDatabases()
  96. rr := request(t, s, "POST", "/v1/account", `{"username":"phil", "password":"mypass"}`, nil)
  97. require.Equal(t, 400, rr.Code)
  98. require.Equal(t, 40022, toHTTPError(t, rr.Body.String()).Code)
  99. }
  100. func TestAccount_Signup_Rate_Limit(t *testing.T) {
  101. conf := newTestConfigWithAuthFile(t)
  102. conf.EnableSignup = true
  103. s := newTestServer(t, conf)
  104. for i := 0; i < 3; i++ {
  105. rr := request(t, s, "POST", "/v1/account", fmt.Sprintf(`{"username":"phil%d", "password":"mypass"}`, i), nil)
  106. require.Equal(t, 200, rr.Code, "failed on iteration %d", i)
  107. }
  108. rr := request(t, s, "POST", "/v1/account", `{"username":"notallowed", "password":"mypass"}`, nil)
  109. require.Equal(t, 429, rr.Code)
  110. require.Equal(t, 42906, toHTTPError(t, rr.Body.String()).Code)
  111. }
  112. func TestAccount_Get_Anonymous(t *testing.T) {
  113. conf := newTestConfigWithAuthFile(t)
  114. conf.VisitorRequestLimitReplenish = 86 * time.Second
  115. conf.VisitorEmailLimitReplenish = time.Hour
  116. conf.VisitorAttachmentTotalSizeLimit = 5123
  117. conf.AttachmentFileSizeLimit = 512
  118. s := newTestServer(t, conf)
  119. s.smtpSender = &testMailer{}
  120. defer s.closeDatabases()
  121. rr := request(t, s, "GET", "/v1/account", "", nil)
  122. require.Equal(t, 200, rr.Code)
  123. account, _ := util.UnmarshalJSON[apiAccountResponse](io.NopCloser(rr.Body))
  124. require.Equal(t, "*", account.Username)
  125. require.Equal(t, string(user.RoleAnonymous), account.Role)
  126. require.Equal(t, "ip", account.Limits.Basis)
  127. require.Equal(t, int64(1004), account.Limits.Messages) // I hate this
  128. require.Equal(t, int64(24), account.Limits.Emails) // I hate this
  129. require.Equal(t, int64(5123), account.Limits.AttachmentTotalSize)
  130. require.Equal(t, int64(512), account.Limits.AttachmentFileSize)
  131. require.Equal(t, int64(0), account.Stats.Messages)
  132. require.Equal(t, int64(1004), account.Stats.MessagesRemaining)
  133. require.Equal(t, int64(0), account.Stats.Emails)
  134. require.Equal(t, int64(24), account.Stats.EmailsRemaining)
  135. rr = request(t, s, "POST", "/mytopic", "", nil)
  136. require.Equal(t, 200, rr.Code)
  137. rr = request(t, s, "POST", "/mytopic", "", map[string]string{
  138. "Email": "phil@ntfy.sh",
  139. })
  140. require.Equal(t, 200, rr.Code)
  141. rr = request(t, s, "GET", "/v1/account", "", nil)
  142. require.Equal(t, 200, rr.Code)
  143. account, _ = util.UnmarshalJSON[apiAccountResponse](io.NopCloser(rr.Body))
  144. require.Equal(t, int64(2), account.Stats.Messages)
  145. require.Equal(t, int64(1002), account.Stats.MessagesRemaining)
  146. require.Equal(t, int64(1), account.Stats.Emails)
  147. require.Equal(t, int64(23), account.Stats.EmailsRemaining)
  148. }
  149. func TestAccount_ChangeSettings(t *testing.T) {
  150. s := newTestServer(t, newTestConfigWithAuthFile(t))
  151. defer s.closeDatabases()
  152. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser))
  153. u, _ := s.userManager.User("phil")
  154. token, _ := s.userManager.CreateToken(u.ID, "", time.Unix(0, 0), netip.IPv4Unspecified())
  155. rr := request(t, s, "PATCH", "/v1/account/settings", `{"notification": {"sound": "juntos"},"ignored": true}`, map[string]string{
  156. "Authorization": util.BasicAuth("phil", "phil"),
  157. })
  158. require.Equal(t, 200, rr.Code)
  159. rr = request(t, s, "PATCH", "/v1/account/settings", `{"notification": {"delete_after": 86400}, "language": "de"}`, map[string]string{
  160. "Authorization": util.BearerAuth(token.Value),
  161. })
  162. require.Equal(t, 200, rr.Code)
  163. rr = request(t, s, "GET", "/v1/account", `{"username":"marian", "password":"marian"}`, map[string]string{
  164. "Authorization": util.BearerAuth(token.Value),
  165. })
  166. require.Equal(t, 200, rr.Code)
  167. account, _ := util.UnmarshalJSON[apiAccountResponse](io.NopCloser(rr.Body))
  168. require.Equal(t, "de", account.Language)
  169. require.Equal(t, util.Int(86400), account.Notification.DeleteAfter)
  170. require.Equal(t, util.String("juntos"), account.Notification.Sound)
  171. require.Nil(t, account.Notification.MinPriority) // Not set
  172. }
  173. func TestAccount_Subscription_AddUpdateDelete(t *testing.T) {
  174. s := newTestServer(t, newTestConfigWithAuthFile(t))
  175. defer s.closeDatabases()
  176. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser))
  177. rr := request(t, s, "POST", "/v1/account/subscription", `{"base_url": "http://abc.com", "topic": "def"}`, map[string]string{
  178. "Authorization": util.BasicAuth("phil", "phil"),
  179. })
  180. require.Equal(t, 200, rr.Code)
  181. rr = request(t, s, "GET", "/v1/account", "", map[string]string{
  182. "Authorization": util.BasicAuth("phil", "phil"),
  183. })
  184. require.Equal(t, 200, rr.Code)
  185. account, _ := util.UnmarshalJSON[apiAccountResponse](io.NopCloser(rr.Body))
  186. require.Equal(t, 1, len(account.Subscriptions))
  187. require.Equal(t, "http://abc.com", account.Subscriptions[0].BaseURL)
  188. require.Equal(t, "def", account.Subscriptions[0].Topic)
  189. require.Nil(t, account.Subscriptions[0].DisplayName)
  190. rr = request(t, s, "PATCH", "/v1/account/subscription", `{"base_url": "http://abc.com", "topic": "def", "display_name": "ding dong"}`, map[string]string{
  191. "Authorization": util.BasicAuth("phil", "phil"),
  192. })
  193. require.Equal(t, 200, rr.Code)
  194. rr = request(t, s, "GET", "/v1/account", "", map[string]string{
  195. "Authorization": util.BasicAuth("phil", "phil"),
  196. })
  197. require.Equal(t, 200, rr.Code)
  198. account, _ = util.UnmarshalJSON[apiAccountResponse](io.NopCloser(rr.Body))
  199. require.Equal(t, 1, len(account.Subscriptions))
  200. require.Equal(t, "http://abc.com", account.Subscriptions[0].BaseURL)
  201. require.Equal(t, "def", account.Subscriptions[0].Topic)
  202. require.Equal(t, util.String("ding dong"), account.Subscriptions[0].DisplayName)
  203. rr = request(t, s, "DELETE", "/v1/account/subscription", "", map[string]string{
  204. "Authorization": util.BasicAuth("phil", "phil"),
  205. "X-BaseURL": "http://abc.com",
  206. "X-Topic": "def",
  207. })
  208. require.Equal(t, 200, rr.Code)
  209. rr = request(t, s, "GET", "/v1/account", "", map[string]string{
  210. "Authorization": util.BasicAuth("phil", "phil"),
  211. })
  212. require.Equal(t, 200, rr.Code)
  213. account, _ = util.UnmarshalJSON[apiAccountResponse](io.NopCloser(rr.Body))
  214. require.Equal(t, 0, len(account.Subscriptions))
  215. }
  216. func TestAccount_ChangePassword(t *testing.T) {
  217. s := newTestServer(t, newTestConfigWithAuthFile(t))
  218. defer s.closeDatabases()
  219. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser))
  220. rr := request(t, s, "POST", "/v1/account/password", `{"password": "WRONG", "new_password": ""}`, map[string]string{
  221. "Authorization": util.BasicAuth("phil", "phil"),
  222. })
  223. require.Equal(t, 400, rr.Code)
  224. rr = request(t, s, "POST", "/v1/account/password", `{"password": "WRONG", "new_password": "new password"}`, map[string]string{
  225. "Authorization": util.BasicAuth("phil", "phil"),
  226. })
  227. require.Equal(t, 400, rr.Code)
  228. require.Equal(t, 40026, toHTTPError(t, rr.Body.String()).Code)
  229. rr = request(t, s, "POST", "/v1/account/password", `{"password": "phil", "new_password": "new password"}`, map[string]string{
  230. "Authorization": util.BasicAuth("phil", "phil"),
  231. })
  232. require.Equal(t, 200, rr.Code)
  233. rr = request(t, s, "GET", "/v1/account", "", map[string]string{
  234. "Authorization": util.BasicAuth("phil", "phil"),
  235. })
  236. require.Equal(t, 401, rr.Code)
  237. rr = request(t, s, "GET", "/v1/account", "", map[string]string{
  238. "Authorization": util.BasicAuth("phil", "new password"),
  239. })
  240. require.Equal(t, 200, rr.Code)
  241. }
  242. func TestAccount_ChangePassword_NoAccount(t *testing.T) {
  243. s := newTestServer(t, newTestConfigWithAuthFile(t))
  244. defer s.closeDatabases()
  245. rr := request(t, s, "POST", "/v1/account/password", `{"password": "new password"}`, nil)
  246. require.Equal(t, 401, rr.Code)
  247. }
  248. func TestAccount_ExtendToken(t *testing.T) {
  249. t.Parallel()
  250. s := newTestServer(t, newTestConfigWithAuthFile(t))
  251. defer s.closeDatabases()
  252. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser))
  253. rr := request(t, s, "POST", "/v1/account/token", "", map[string]string{
  254. "Authorization": util.BasicAuth("phil", "phil"),
  255. })
  256. require.Equal(t, 200, rr.Code)
  257. token, err := util.UnmarshalJSON[apiAccountTokenResponse](io.NopCloser(rr.Body))
  258. require.Nil(t, err)
  259. time.Sleep(time.Second)
  260. rr = request(t, s, "PATCH", "/v1/account/token", "", map[string]string{
  261. "Authorization": util.BearerAuth(token.Token),
  262. })
  263. require.Equal(t, 200, rr.Code)
  264. extendedToken, err := util.UnmarshalJSON[apiAccountTokenResponse](io.NopCloser(rr.Body))
  265. require.Nil(t, err)
  266. require.Equal(t, token.Token, extendedToken.Token)
  267. require.True(t, token.Expires < extendedToken.Expires)
  268. expires := time.Now().Add(999 * time.Hour)
  269. body := fmt.Sprintf(`{"token":"%s", "label":"some label", "expires": %d}`, token.Token, expires.Unix())
  270. rr = request(t, s, "PATCH", "/v1/account/token", body, map[string]string{
  271. "Authorization": util.BearerAuth(token.Token),
  272. })
  273. require.Equal(t, 200, rr.Code)
  274. token, err = util.UnmarshalJSON[apiAccountTokenResponse](io.NopCloser(rr.Body))
  275. require.Nil(t, err)
  276. require.Equal(t, "some label", token.Label)
  277. require.Equal(t, expires.Unix(), token.Expires)
  278. }
  279. func TestAccount_ExtendToken_NoTokenProvided(t *testing.T) {
  280. s := newTestServer(t, newTestConfigWithAuthFile(t))
  281. defer s.closeDatabases()
  282. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser))
  283. rr := request(t, s, "PATCH", "/v1/account/token", "", map[string]string{
  284. "Authorization": util.BasicAuth("phil", "phil"), // Not Bearer!
  285. })
  286. require.Equal(t, 400, rr.Code)
  287. require.Equal(t, 40023, toHTTPError(t, rr.Body.String()).Code)
  288. }
  289. func TestAccount_DeleteToken(t *testing.T) {
  290. s := newTestServer(t, newTestConfigWithAuthFile(t))
  291. defer s.closeDatabases()
  292. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser))
  293. rr := request(t, s, "POST", "/v1/account/token", "", map[string]string{
  294. "Authorization": util.BasicAuth("phil", "phil"),
  295. })
  296. require.Equal(t, 200, rr.Code)
  297. token, err := util.UnmarshalJSON[apiAccountTokenResponse](io.NopCloser(rr.Body))
  298. require.Nil(t, err)
  299. require.True(t, token.Expires > time.Now().Add(71*time.Hour).Unix())
  300. // Delete token failure (using basic auth)
  301. rr = request(t, s, "DELETE", "/v1/account/token", "", map[string]string{
  302. "Authorization": util.BasicAuth("phil", "phil"), // Not Bearer!
  303. })
  304. require.Equal(t, 400, rr.Code)
  305. require.Equal(t, 40023, toHTTPError(t, rr.Body.String()).Code)
  306. // Delete token with wrong token
  307. rr = request(t, s, "DELETE", "/v1/account/token", "", map[string]string{
  308. "Authorization": util.BearerAuth("invalidtoken"),
  309. })
  310. require.Equal(t, 401, rr.Code)
  311. // Delete token with correct token
  312. rr = request(t, s, "DELETE", "/v1/account/token", "", map[string]string{
  313. "Authorization": util.BearerAuth(token.Token),
  314. })
  315. require.Equal(t, 200, rr.Code)
  316. // Cannot get account anymore
  317. rr = request(t, s, "GET", "/v1/account", "", map[string]string{
  318. "Authorization": util.BearerAuth(token.Token),
  319. })
  320. require.Equal(t, 401, rr.Code)
  321. }
  322. func TestAccount_Delete_Success(t *testing.T) {
  323. conf := newTestConfigWithAuthFile(t)
  324. conf.EnableSignup = true
  325. s := newTestServer(t, conf)
  326. rr := request(t, s, "POST", "/v1/account", `{"username":"phil", "password":"mypass"}`, nil)
  327. require.Equal(t, 200, rr.Code)
  328. rr = request(t, s, "GET", "/v1/account", "", map[string]string{
  329. "Authorization": util.BasicAuth("phil", "mypass"),
  330. })
  331. require.Equal(t, 200, rr.Code)
  332. rr = request(t, s, "DELETE", "/v1/account", `{"password":"mypass"}`, map[string]string{
  333. "Authorization": util.BasicAuth("phil", "mypass"),
  334. })
  335. require.Equal(t, 200, rr.Code)
  336. // Account was marked deleted
  337. rr = request(t, s, "GET", "/v1/account", "", map[string]string{
  338. "Authorization": util.BasicAuth("phil", "mypass"),
  339. })
  340. require.Equal(t, 401, rr.Code)
  341. // Cannot re-create account, since still exists
  342. rr = request(t, s, "POST", "/v1/account", `{"username":"phil", "password":"mypass"}`, nil)
  343. require.Equal(t, 409, rr.Code)
  344. }
  345. func TestAccount_Delete_Not_Allowed(t *testing.T) {
  346. conf := newTestConfigWithAuthFile(t)
  347. conf.EnableSignup = true
  348. s := newTestServer(t, conf)
  349. rr := request(t, s, "POST", "/v1/account", `{"username":"phil", "password":"mypass"}`, nil)
  350. require.Equal(t, 200, rr.Code)
  351. rr = request(t, s, "DELETE", "/v1/account", "", nil)
  352. require.Equal(t, 401, rr.Code)
  353. rr = request(t, s, "DELETE", "/v1/account", `{"password":"mypass"}`, nil)
  354. require.Equal(t, 401, rr.Code)
  355. rr = request(t, s, "DELETE", "/v1/account", `{"password":"INCORRECT"}`, map[string]string{
  356. "Authorization": util.BasicAuth("phil", "mypass"),
  357. })
  358. require.Equal(t, 400, rr.Code)
  359. require.Equal(t, 40026, toHTTPError(t, rr.Body.String()).Code)
  360. }
  361. func TestAccount_Reservation_AddWithoutTierFails(t *testing.T) {
  362. conf := newTestConfigWithAuthFile(t)
  363. conf.EnableSignup = true
  364. s := newTestServer(t, conf)
  365. rr := request(t, s, "POST", "/v1/account", `{"username":"phil", "password":"mypass"}`, nil)
  366. require.Equal(t, 200, rr.Code)
  367. rr = request(t, s, "POST", "/v1/account/reservation", `{"topic":"mytopic", "everyone":"deny-all"}`, map[string]string{
  368. "Authorization": util.BasicAuth("phil", "mypass"),
  369. })
  370. require.Equal(t, 401, rr.Code)
  371. }
  372. func TestAccount_Reservation_AddAdminSuccess(t *testing.T) {
  373. conf := newTestConfigWithAuthFile(t)
  374. conf.EnableSignup = true
  375. s := newTestServer(t, conf)
  376. // A user, an admin, and a reservation walk into a bar
  377. require.Nil(t, s.userManager.AddTier(&user.Tier{
  378. Code: "pro",
  379. ReservationLimit: 2,
  380. }))
  381. require.Nil(t, s.userManager.AddUser("noadmin1", "pass", user.RoleUser))
  382. require.Nil(t, s.userManager.ChangeTier("noadmin1", "pro"))
  383. require.Nil(t, s.userManager.AddReservation("noadmin1", "mytopic", user.PermissionDenyAll))
  384. require.Nil(t, s.userManager.AddUser("noadmin2", "pass", user.RoleUser))
  385. require.Nil(t, s.userManager.ChangeTier("noadmin2", "pro"))
  386. require.Nil(t, s.userManager.AddUser("phil", "adminpass", user.RoleAdmin))
  387. // Admin can reserve topic
  388. rr := request(t, s, "POST", "/v1/account/reservation", `{"topic":"sometopic","everyone":"deny-all"}`, map[string]string{
  389. "Authorization": util.BasicAuth("phil", "adminpass"),
  390. })
  391. require.Equal(t, 200, rr.Code)
  392. // User cannot reserve already reserved topic
  393. rr = request(t, s, "POST", "/v1/account/reservation", `{"topic":"mytopic","everyone":"deny-all"}`, map[string]string{
  394. "Authorization": util.BasicAuth("noadmin2", "pass"),
  395. })
  396. require.Equal(t, 409, rr.Code)
  397. // Admin cannot reserve already reserved topic
  398. rr = request(t, s, "POST", "/v1/account/reservation", `{"topic":"mytopic","everyone":"deny-all"}`, map[string]string{
  399. "Authorization": util.BasicAuth("phil", "adminpass"),
  400. })
  401. require.Equal(t, 409, rr.Code)
  402. reservations, err := s.userManager.Reservations("phil")
  403. require.Nil(t, err)
  404. require.Equal(t, 1, len(reservations))
  405. require.Equal(t, "sometopic", reservations[0].Topic)
  406. reservations, err = s.userManager.Reservations("noadmin1")
  407. require.Nil(t, err)
  408. require.Equal(t, 1, len(reservations))
  409. require.Equal(t, "mytopic", reservations[0].Topic)
  410. reservations, err = s.userManager.Reservations("noadmin2")
  411. require.Nil(t, err)
  412. require.Equal(t, 0, len(reservations))
  413. }
  414. func TestAccount_Reservation_AddRemoveUserWithTierSuccess(t *testing.T) {
  415. conf := newTestConfigWithAuthFile(t)
  416. conf.EnableSignup = true
  417. s := newTestServer(t, conf)
  418. // Create user
  419. rr := request(t, s, "POST", "/v1/account", `{"username":"phil", "password":"mypass"}`, nil)
  420. require.Equal(t, 200, rr.Code)
  421. // Create a tier
  422. require.Nil(t, s.userManager.AddTier(&user.Tier{
  423. Code: "pro",
  424. MessageLimit: 123,
  425. MessageExpiryDuration: 86400 * time.Second,
  426. EmailLimit: 32,
  427. ReservationLimit: 2,
  428. AttachmentFileSizeLimit: 1231231,
  429. AttachmentTotalSizeLimit: 123123,
  430. AttachmentExpiryDuration: 10800 * time.Second,
  431. AttachmentBandwidthLimit: 21474836480,
  432. }))
  433. require.Nil(t, s.userManager.ChangeTier("phil", "pro"))
  434. // Reserve two topics
  435. rr = request(t, s, "POST", "/v1/account/reservation", `{"topic": "mytopic", "everyone":"deny-all"}`, map[string]string{
  436. "Authorization": util.BasicAuth("phil", "mypass"),
  437. })
  438. require.Equal(t, 200, rr.Code)
  439. rr = request(t, s, "POST", "/v1/account/reservation", `{"topic": "another", "everyone":"read-only"}`, map[string]string{
  440. "Authorization": util.BasicAuth("phil", "mypass"),
  441. })
  442. require.Equal(t, 200, rr.Code)
  443. // Trying to reserve a third should fail
  444. rr = request(t, s, "POST", "/v1/account/reservation", `{"topic": "yet-another", "everyone":"deny-all"}`, map[string]string{
  445. "Authorization": util.BasicAuth("phil", "mypass"),
  446. })
  447. require.Equal(t, 429, rr.Code)
  448. // Modify existing should still work
  449. rr = request(t, s, "POST", "/v1/account/reservation", `{"topic": "another", "everyone":"write-only"}`, map[string]string{
  450. "Authorization": util.BasicAuth("phil", "mypass"),
  451. })
  452. require.Equal(t, 200, rr.Code)
  453. // Check account result
  454. rr = request(t, s, "GET", "/v1/account", "", map[string]string{
  455. "Authorization": util.BasicAuth("phil", "mypass"),
  456. })
  457. require.Equal(t, 200, rr.Code)
  458. account, _ := util.UnmarshalJSON[apiAccountResponse](io.NopCloser(rr.Body))
  459. require.Equal(t, "pro", account.Tier.Code)
  460. require.Equal(t, int64(123), account.Limits.Messages)
  461. require.Equal(t, int64(86400), account.Limits.MessagesExpiryDuration)
  462. require.Equal(t, int64(32), account.Limits.Emails)
  463. require.Equal(t, int64(2), account.Limits.Reservations)
  464. require.Equal(t, int64(1231231), account.Limits.AttachmentFileSize)
  465. require.Equal(t, int64(123123), account.Limits.AttachmentTotalSize)
  466. require.Equal(t, int64(10800), account.Limits.AttachmentExpiryDuration)
  467. require.Equal(t, int64(21474836480), account.Limits.AttachmentBandwidth)
  468. require.Equal(t, 2, len(account.Reservations))
  469. require.Equal(t, "another", account.Reservations[0].Topic)
  470. require.Equal(t, "write-only", account.Reservations[0].Everyone)
  471. require.Equal(t, "mytopic", account.Reservations[1].Topic)
  472. require.Equal(t, "deny-all", account.Reservations[1].Everyone)
  473. // Delete and re-check
  474. rr = request(t, s, "DELETE", "/v1/account/reservation/another", "", map[string]string{
  475. "Authorization": util.BasicAuth("phil", "mypass"),
  476. })
  477. require.Equal(t, 200, rr.Code)
  478. rr = request(t, s, "GET", "/v1/account", "", map[string]string{
  479. "Authorization": util.BasicAuth("phil", "mypass"),
  480. })
  481. require.Equal(t, 200, rr.Code)
  482. account, _ = util.UnmarshalJSON[apiAccountResponse](io.NopCloser(rr.Body))
  483. require.Equal(t, 1, len(account.Reservations))
  484. require.Equal(t, "mytopic", account.Reservations[0].Topic)
  485. }
  486. func TestAccount_Reservation_PublishByAnonymousFails(t *testing.T) {
  487. conf := newTestConfigWithAuthFile(t)
  488. conf.AuthDefault = user.PermissionReadWrite
  489. conf.EnableSignup = true
  490. s := newTestServer(t, conf)
  491. // Create user with tier
  492. rr := request(t, s, "POST", "/v1/account", `{"username":"phil", "password":"mypass"}`, nil)
  493. require.Equal(t, 200, rr.Code)
  494. require.Nil(t, s.userManager.AddTier(&user.Tier{
  495. Code: "pro",
  496. MessageLimit: 20,
  497. ReservationLimit: 2,
  498. }))
  499. require.Nil(t, s.userManager.ChangeTier("phil", "pro"))
  500. // Reserve a topic
  501. rr = request(t, s, "POST", "/v1/account/reservation", `{"topic": "mytopic", "everyone":"deny-all"}`, map[string]string{
  502. "Authorization": util.BasicAuth("phil", "mypass"),
  503. })
  504. require.Equal(t, 200, rr.Code)
  505. // Publish a message
  506. rr = request(t, s, "POST", "/mytopic", `Howdy`, map[string]string{
  507. "Authorization": util.BasicAuth("phil", "mypass"),
  508. })
  509. require.Equal(t, 200, rr.Code)
  510. // Publish a message (as anonymous)
  511. rr = request(t, s, "POST", "/mytopic", `Howdy`, nil)
  512. require.Equal(t, 403, rr.Code)
  513. }
  514. func TestAccount_Reservation_Delete_Messages_And_Attachments(t *testing.T) {
  515. t.Parallel()
  516. conf := newTestConfigWithAuthFile(t)
  517. conf.AuthDefault = user.PermissionReadWrite
  518. s := newTestServer(t, conf)
  519. // Create user with tier
  520. require.Nil(t, s.userManager.AddUser("phil", "mypass", user.RoleUser))
  521. require.Nil(t, s.userManager.AddTier(&user.Tier{
  522. Code: "pro",
  523. MessageLimit: 20,
  524. MessageExpiryDuration: time.Hour,
  525. ReservationLimit: 2,
  526. AttachmentTotalSizeLimit: 10000,
  527. AttachmentFileSizeLimit: 10000,
  528. AttachmentExpiryDuration: time.Hour,
  529. AttachmentBandwidthLimit: 10000,
  530. }))
  531. require.Nil(t, s.userManager.ChangeTier("phil", "pro"))
  532. // Reserve two topics "mytopic1" and "mytopic2"
  533. rr := request(t, s, "POST", "/v1/account/reservation", `{"topic": "mytopic1", "everyone":"deny-all"}`, map[string]string{
  534. "Authorization": util.BasicAuth("phil", "mypass"),
  535. })
  536. require.Equal(t, 200, rr.Code)
  537. rr = request(t, s, "POST", "/v1/account/reservation", `{"topic": "mytopic2", "everyone":"deny-all"}`, map[string]string{
  538. "Authorization": util.BasicAuth("phil", "mypass"),
  539. })
  540. require.Equal(t, 200, rr.Code)
  541. // Publish a message with attachment to each topic
  542. rr = request(t, s, "POST", "/mytopic1?f=attach.txt", `Howdy`, map[string]string{
  543. "Authorization": util.BasicAuth("phil", "mypass"),
  544. })
  545. require.Equal(t, 200, rr.Code)
  546. m1 := toMessage(t, rr.Body.String())
  547. require.FileExists(t, filepath.Join(s.config.AttachmentCacheDir, m1.ID))
  548. rr = request(t, s, "POST", "/mytopic2?f=attach.txt", `Howdy`, map[string]string{
  549. "Authorization": util.BasicAuth("phil", "mypass"),
  550. })
  551. require.Equal(t, 200, rr.Code)
  552. m2 := toMessage(t, rr.Body.String())
  553. require.FileExists(t, filepath.Join(s.config.AttachmentCacheDir, m2.ID))
  554. // Pre-verify message count and file
  555. ms, err := s.messageCache.Messages("mytopic1", sinceAllMessages, false)
  556. require.Nil(t, err)
  557. require.Equal(t, 1, len(ms))
  558. require.FileExists(t, filepath.Join(s.config.AttachmentCacheDir, m1.ID))
  559. ms, err = s.messageCache.Messages("mytopic2", sinceAllMessages, false)
  560. require.Nil(t, err)
  561. require.Equal(t, 1, len(ms))
  562. require.FileExists(t, filepath.Join(s.config.AttachmentCacheDir, m2.ID))
  563. // Delete reservation
  564. rr = request(t, s, "DELETE", "/v1/account/reservation/mytopic1", ``, map[string]string{
  565. "X-Delete-Messages": "true",
  566. "Authorization": util.BasicAuth("phil", "mypass"),
  567. })
  568. require.Equal(t, 200, rr.Code)
  569. rr = request(t, s, "DELETE", "/v1/account/reservation/mytopic2", ``, map[string]string{
  570. "X-Delete-Messages": "false",
  571. "Authorization": util.BasicAuth("phil", "mypass"),
  572. })
  573. require.Equal(t, 200, rr.Code)
  574. // Verify that messages and attachments were deleted
  575. // This does not explicitly call the manager!
  576. waitFor(t, func() bool {
  577. ms, err := s.messageCache.Messages("mytopic1", sinceAllMessages, false)
  578. require.Nil(t, err)
  579. return len(ms) == 0 && !util.FileExists(filepath.Join(s.config.AttachmentCacheDir, m1.ID))
  580. })
  581. ms, err = s.messageCache.Messages("mytopic1", sinceAllMessages, false)
  582. require.Nil(t, err)
  583. require.Equal(t, 0, len(ms))
  584. require.NoFileExists(t, filepath.Join(s.config.AttachmentCacheDir, m1.ID))
  585. ms, err = s.messageCache.Messages("mytopic2", sinceAllMessages, false)
  586. require.Nil(t, err)
  587. require.Equal(t, 1, len(ms))
  588. require.Equal(t, m2.ID, ms[0].ID)
  589. require.FileExists(t, filepath.Join(s.config.AttachmentCacheDir, m2.ID))
  590. }
  591. func TestAccount_Persist_UserStats_After_Tier_Change(t *testing.T) {
  592. t.Parallel()
  593. conf := newTestConfigWithAuthFile(t)
  594. conf.AuthDefault = user.PermissionReadWrite
  595. conf.AuthStatsQueueWriterInterval = 100 * time.Millisecond
  596. s := newTestServer(t, conf)
  597. defer s.closeDatabases()
  598. // Create user with tier
  599. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser))
  600. require.Nil(t, s.userManager.AddTier(&user.Tier{
  601. Code: "starter",
  602. MessageLimit: 10,
  603. }))
  604. require.Nil(t, s.userManager.AddTier(&user.Tier{
  605. Code: "pro",
  606. MessageLimit: 20,
  607. }))
  608. require.Nil(t, s.userManager.ChangeTier("phil", "starter"))
  609. // Publish a message
  610. rr := request(t, s, "POST", "/mytopic", "hi", map[string]string{
  611. "Authorization": util.BasicAuth("phil", "phil"),
  612. })
  613. require.Equal(t, 200, rr.Code)
  614. // Wait for stats queue writer, verify that message stats were persisted
  615. waitFor(t, func() bool {
  616. u, err := s.userManager.User("phil")
  617. require.Nil(t, err)
  618. return int64(1) == u.Stats.Messages
  619. })
  620. // Change tier, make a request (to reset limiters)
  621. require.Nil(t, s.userManager.ChangeTier("phil", "pro"))
  622. rr = request(t, s, "GET", "/v1/account", "", map[string]string{
  623. "Authorization": util.BasicAuth("phil", "phil"),
  624. })
  625. require.Equal(t, 200, rr.Code)
  626. account, _ := util.UnmarshalJSON[apiAccountResponse](io.NopCloser(rr.Body))
  627. require.Equal(t, int64(1), account.Stats.Messages) // Is not reset!
  628. // Publish another message
  629. rr = request(t, s, "POST", "/mytopic", "hi", map[string]string{
  630. "Authorization": util.BasicAuth("phil", "phil"),
  631. })
  632. require.Equal(t, 200, rr.Code)
  633. // Verify that message stats were persisted
  634. waitFor(t, func() bool {
  635. u, err := s.userManager.User("phil")
  636. require.Nil(t, err)
  637. return int64(2) == u.Stats.Messages // v.EnqueueUserStats had run!
  638. })
  639. // Stats keep counting
  640. rr = request(t, s, "GET", "/v1/account", "", map[string]string{
  641. "Authorization": util.BasicAuth("phil", "phil"),
  642. })
  643. require.Equal(t, 200, rr.Code)
  644. account, _ = util.UnmarshalJSON[apiAccountResponse](io.NopCloser(rr.Body))
  645. require.Equal(t, int64(2), account.Stats.Messages) // Is not reset!
  646. }