server_account.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. package server
  2. import (
  3. "encoding/json"
  4. "heckel.io/ntfy/log"
  5. "heckel.io/ntfy/user"
  6. "heckel.io/ntfy/util"
  7. "net/http"
  8. "strings"
  9. "time"
  10. )
  11. const (
  12. subscriptionIDLength = 16
  13. subscriptionIDPrefix = "su_"
  14. syncTopicAccountSyncEvent = "sync"
  15. tokenExpiryDuration = 72 * time.Hour // Extend tokens by this much
  16. )
  17. func (s *Server) handleAccountCreate(w http.ResponseWriter, r *http.Request, v *visitor) error {
  18. admin := v.user != nil && v.user.Role == user.RoleAdmin
  19. if !admin {
  20. if !s.config.EnableSignup {
  21. return errHTTPBadRequestSignupNotEnabled
  22. } else if v.user != nil {
  23. return errHTTPUnauthorized // Cannot create account from user context
  24. }
  25. if !v.AccountCreationAllowed() {
  26. return errHTTPTooManyRequestsLimitAccountCreation
  27. }
  28. }
  29. newAccount, err := readJSONWithLimit[apiAccountCreateRequest](r.Body, jsonBodyBytesLimit, false)
  30. if err != nil {
  31. return err
  32. }
  33. if existingUser, _ := s.userManager.User(newAccount.Username); existingUser != nil {
  34. return errHTTPConflictUserExists
  35. }
  36. if err := s.userManager.AddUser(newAccount.Username, newAccount.Password, user.RoleUser); err != nil { // TODO this should return a User
  37. return err
  38. }
  39. return s.writeJSON(w, newSuccessResponse())
  40. }
  41. func (s *Server) handleAccountGet(w http.ResponseWriter, _ *http.Request, v *visitor) error {
  42. info, err := v.Info()
  43. if err != nil {
  44. return err
  45. }
  46. limits, stats := info.Limits, info.Stats
  47. response := &apiAccountResponse{
  48. Limits: &apiAccountLimits{
  49. Basis: string(limits.Basis),
  50. Messages: limits.MessageLimit,
  51. MessagesExpiryDuration: int64(limits.MessageExpiryDuration.Seconds()),
  52. Emails: limits.EmailLimit,
  53. Reservations: limits.ReservationsLimit,
  54. AttachmentTotalSize: limits.AttachmentTotalSizeLimit,
  55. AttachmentFileSize: limits.AttachmentFileSizeLimit,
  56. AttachmentExpiryDuration: int64(limits.AttachmentExpiryDuration.Seconds()),
  57. AttachmentBandwidth: limits.AttachmentBandwidthLimit,
  58. },
  59. Stats: &apiAccountStats{
  60. Messages: stats.Messages,
  61. MessagesRemaining: stats.MessagesRemaining,
  62. Emails: stats.Emails,
  63. EmailsRemaining: stats.EmailsRemaining,
  64. Reservations: stats.Reservations,
  65. ReservationsRemaining: stats.ReservationsRemaining,
  66. AttachmentTotalSize: stats.AttachmentTotalSize,
  67. AttachmentTotalSizeRemaining: stats.AttachmentTotalSizeRemaining,
  68. },
  69. }
  70. u := v.User()
  71. if u != nil {
  72. response.Username = u.Name
  73. response.Role = string(u.Role)
  74. response.SyncTopic = u.SyncTopic
  75. if u.Prefs != nil {
  76. if u.Prefs.Language != nil {
  77. response.Language = *u.Prefs.Language
  78. }
  79. if u.Prefs.Notification != nil {
  80. response.Notification = u.Prefs.Notification
  81. }
  82. if u.Prefs.Subscriptions != nil {
  83. response.Subscriptions = u.Prefs.Subscriptions
  84. }
  85. }
  86. if u.Tier != nil {
  87. response.Tier = &apiAccountTier{
  88. Code: u.Tier.Code,
  89. Name: u.Tier.Name,
  90. }
  91. }
  92. if u.Billing.StripeCustomerID != "" {
  93. response.Billing = &apiAccountBilling{
  94. Customer: true,
  95. Subscription: u.Billing.StripeSubscriptionID != "",
  96. Status: string(u.Billing.StripeSubscriptionStatus),
  97. PaidUntil: u.Billing.StripeSubscriptionPaidUntil.Unix(),
  98. CancelAt: u.Billing.StripeSubscriptionCancelAt.Unix(),
  99. }
  100. }
  101. reservations, err := s.userManager.Reservations(u.Name)
  102. if err != nil {
  103. return err
  104. }
  105. if len(reservations) > 0 {
  106. response.Reservations = make([]*apiAccountReservation, 0)
  107. for _, r := range reservations {
  108. response.Reservations = append(response.Reservations, &apiAccountReservation{
  109. Topic: r.Topic,
  110. Everyone: r.Everyone.String(),
  111. })
  112. }
  113. }
  114. tokens, err := s.userManager.Tokens(u.ID)
  115. if err != nil {
  116. return err
  117. }
  118. if len(tokens) > 0 {
  119. response.Tokens = make([]*apiAccountTokenResponse, 0)
  120. for _, t := range tokens {
  121. response.Tokens = append(response.Tokens, &apiAccountTokenResponse{
  122. Token: t.Value,
  123. Label: t.Label,
  124. Expires: t.Expires.Unix(),
  125. })
  126. }
  127. }
  128. } else {
  129. response.Username = user.Everyone
  130. response.Role = string(user.RoleAnonymous)
  131. }
  132. return s.writeJSON(w, response)
  133. }
  134. func (s *Server) handleAccountDelete(w http.ResponseWriter, r *http.Request, v *visitor) error {
  135. req, err := readJSONWithLimit[apiAccountDeleteRequest](r.Body, jsonBodyBytesLimit, false)
  136. if err != nil {
  137. return err
  138. } else if req.Password == "" {
  139. return errHTTPBadRequest
  140. }
  141. if _, err := s.userManager.Authenticate(v.user.Name, req.Password); err != nil {
  142. return errHTTPBadRequestIncorrectPasswordConfirmation
  143. }
  144. if v.user.Billing.StripeSubscriptionID != "" {
  145. log.Info("%s Canceling billing subscription %s", logHTTPPrefix(v, r), v.user.Billing.StripeSubscriptionID)
  146. if _, err := s.stripe.CancelSubscription(v.user.Billing.StripeSubscriptionID); err != nil {
  147. return err
  148. }
  149. }
  150. if err := s.maybeRemoveMessagesAndExcessReservations(logHTTPPrefix(v, r), v.user, 0); err != nil {
  151. return err
  152. }
  153. log.Info("%s Marking user %s as deleted", logHTTPPrefix(v, r), v.user.Name)
  154. if err := s.userManager.MarkUserRemoved(v.user); err != nil {
  155. return err
  156. }
  157. return s.writeJSON(w, newSuccessResponse())
  158. }
  159. func (s *Server) handleAccountPasswordChange(w http.ResponseWriter, r *http.Request, v *visitor) error {
  160. req, err := readJSONWithLimit[apiAccountPasswordChangeRequest](r.Body, jsonBodyBytesLimit, false)
  161. if err != nil {
  162. return err
  163. } else if req.Password == "" || req.NewPassword == "" {
  164. return errHTTPBadRequest
  165. }
  166. if _, err := s.userManager.Authenticate(v.user.Name, req.Password); err != nil {
  167. return errHTTPBadRequestIncorrectPasswordConfirmation
  168. }
  169. if err := s.userManager.ChangePassword(v.user.Name, req.NewPassword); err != nil {
  170. return err
  171. }
  172. return s.writeJSON(w, newSuccessResponse())
  173. }
  174. func (s *Server) handleAccountTokenCreate(w http.ResponseWriter, r *http.Request, v *visitor) error {
  175. // TODO rate limit
  176. req, err := readJSONWithLimit[apiAccountTokenIssueRequest](r.Body, jsonBodyBytesLimit, true) // Allow empty body!
  177. if err != nil {
  178. return err
  179. }
  180. var label string
  181. if req.Label != nil {
  182. label = *req.Label
  183. }
  184. expires := time.Now().Add(tokenExpiryDuration)
  185. if req.Expires != nil {
  186. expires = time.Unix(*req.Expires, 0)
  187. }
  188. token, err := s.userManager.CreateToken(v.User().ID, label, expires)
  189. if err != nil {
  190. return err
  191. }
  192. response := &apiAccountTokenResponse{
  193. Token: token.Value,
  194. Label: token.Label,
  195. Expires: token.Expires.Unix(),
  196. }
  197. return s.writeJSON(w, response)
  198. }
  199. func (s *Server) handleAccountTokenUpdate(w http.ResponseWriter, r *http.Request, v *visitor) error {
  200. // TODO rate limit
  201. u := v.User()
  202. req, err := readJSONWithLimit[apiAccountTokenUpdateRequest](r.Body, jsonBodyBytesLimit, true) // Allow empty body!
  203. if err != nil {
  204. return err
  205. } else if req.Token == "" {
  206. req.Token = u.Token
  207. if req.Token == "" {
  208. return errHTTPBadRequestNoTokenProvided
  209. }
  210. }
  211. var expires *time.Time
  212. if req.Expires != nil {
  213. expires = util.Time(time.Unix(*req.Expires, 0))
  214. } else if req.Label == nil {
  215. // If label and expires are not set, simply extend the token by 72 hours
  216. expires = util.Time(time.Now().Add(tokenExpiryDuration))
  217. }
  218. token, err := s.userManager.ChangeToken(u.ID, req.Token, req.Label, expires)
  219. if err != nil {
  220. return err
  221. }
  222. response := &apiAccountTokenResponse{
  223. Token: token.Value,
  224. Label: token.Label,
  225. Expires: token.Expires.Unix(),
  226. }
  227. return s.writeJSON(w, response)
  228. }
  229. func (s *Server) handleAccountTokenDelete(w http.ResponseWriter, r *http.Request, v *visitor) error {
  230. // TODO rate limit
  231. u := v.User()
  232. token := readParam(r, "X-Token", "Token") // DELETEs cannot have a body, and we don't want it in the path
  233. if token == "" {
  234. token = u.Token
  235. if token == "" {
  236. return errHTTPBadRequestNoTokenProvided
  237. }
  238. }
  239. if err := s.userManager.RemoveToken(u.ID, token); err != nil {
  240. return err
  241. }
  242. return s.writeJSON(w, newSuccessResponse())
  243. }
  244. func (s *Server) handleAccountSettingsChange(w http.ResponseWriter, r *http.Request, v *visitor) error {
  245. newPrefs, err := readJSONWithLimit[user.Prefs](r.Body, jsonBodyBytesLimit, false)
  246. if err != nil {
  247. return err
  248. }
  249. if v.user.Prefs == nil {
  250. v.user.Prefs = &user.Prefs{}
  251. }
  252. prefs := v.user.Prefs
  253. if newPrefs.Language != nil {
  254. prefs.Language = newPrefs.Language
  255. }
  256. if newPrefs.Notification != nil {
  257. if prefs.Notification == nil {
  258. prefs.Notification = &user.NotificationPrefs{}
  259. }
  260. if newPrefs.Notification.DeleteAfter != nil {
  261. prefs.Notification.DeleteAfter = newPrefs.Notification.DeleteAfter
  262. }
  263. if newPrefs.Notification.Sound != nil {
  264. prefs.Notification.Sound = newPrefs.Notification.Sound
  265. }
  266. if newPrefs.Notification.MinPriority != nil {
  267. prefs.Notification.MinPriority = newPrefs.Notification.MinPriority
  268. }
  269. }
  270. if err := s.userManager.ChangeSettings(v.user); err != nil {
  271. return err
  272. }
  273. return s.writeJSON(w, newSuccessResponse())
  274. }
  275. func (s *Server) handleAccountSubscriptionAdd(w http.ResponseWriter, r *http.Request, v *visitor) error {
  276. newSubscription, err := readJSONWithLimit[user.Subscription](r.Body, jsonBodyBytesLimit, false)
  277. if err != nil {
  278. return err
  279. }
  280. if v.user.Prefs == nil {
  281. v.user.Prefs = &user.Prefs{}
  282. }
  283. newSubscription.ID = "" // Client cannot set ID
  284. for _, subscription := range v.user.Prefs.Subscriptions {
  285. if newSubscription.BaseURL == subscription.BaseURL && newSubscription.Topic == subscription.Topic {
  286. newSubscription = subscription
  287. break
  288. }
  289. }
  290. if newSubscription.ID == "" {
  291. newSubscription.ID = util.RandomStringPrefix(subscriptionIDPrefix, subscriptionIDLength)
  292. v.user.Prefs.Subscriptions = append(v.user.Prefs.Subscriptions, newSubscription)
  293. if err := s.userManager.ChangeSettings(v.user); err != nil {
  294. return err
  295. }
  296. }
  297. return s.writeJSON(w, newSubscription)
  298. }
  299. func (s *Server) handleAccountSubscriptionChange(w http.ResponseWriter, r *http.Request, v *visitor) error {
  300. matches := apiAccountSubscriptionSingleRegex.FindStringSubmatch(r.URL.Path)
  301. if len(matches) != 2 {
  302. return errHTTPInternalErrorInvalidPath
  303. }
  304. subscriptionID := matches[1]
  305. updatedSubscription, err := readJSONWithLimit[user.Subscription](r.Body, jsonBodyBytesLimit, false)
  306. if err != nil {
  307. return err
  308. }
  309. if v.user.Prefs == nil || v.user.Prefs.Subscriptions == nil {
  310. return errHTTPNotFound
  311. }
  312. var subscription *user.Subscription
  313. for _, sub := range v.user.Prefs.Subscriptions {
  314. if sub.ID == subscriptionID {
  315. sub.DisplayName = updatedSubscription.DisplayName
  316. subscription = sub
  317. break
  318. }
  319. }
  320. if subscription == nil {
  321. return errHTTPNotFound
  322. }
  323. if err := s.userManager.ChangeSettings(v.user); err != nil {
  324. return err
  325. }
  326. return s.writeJSON(w, subscription)
  327. }
  328. func (s *Server) handleAccountSubscriptionDelete(w http.ResponseWriter, r *http.Request, v *visitor) error {
  329. matches := apiAccountSubscriptionSingleRegex.FindStringSubmatch(r.URL.Path)
  330. if len(matches) != 2 {
  331. return errHTTPInternalErrorInvalidPath
  332. }
  333. subscriptionID := matches[1]
  334. if v.user.Prefs == nil || v.user.Prefs.Subscriptions == nil {
  335. return nil
  336. }
  337. newSubscriptions := make([]*user.Subscription, 0)
  338. for _, subscription := range v.user.Prefs.Subscriptions {
  339. if subscription.ID != subscriptionID {
  340. newSubscriptions = append(newSubscriptions, subscription)
  341. }
  342. }
  343. if len(newSubscriptions) < len(v.user.Prefs.Subscriptions) {
  344. v.user.Prefs.Subscriptions = newSubscriptions
  345. if err := s.userManager.ChangeSettings(v.user); err != nil {
  346. return err
  347. }
  348. }
  349. return s.writeJSON(w, newSuccessResponse())
  350. }
  351. func (s *Server) handleAccountReservationAdd(w http.ResponseWriter, r *http.Request, v *visitor) error {
  352. if v.user != nil && v.user.Role == user.RoleAdmin {
  353. return errHTTPBadRequestMakesNoSenseForAdmin
  354. }
  355. req, err := readJSONWithLimit[apiAccountReservationRequest](r.Body, jsonBodyBytesLimit, false)
  356. if err != nil {
  357. return err
  358. }
  359. if !topicRegex.MatchString(req.Topic) {
  360. return errHTTPBadRequestTopicInvalid
  361. }
  362. everyone, err := user.ParsePermission(req.Everyone)
  363. if err != nil {
  364. return errHTTPBadRequestPermissionInvalid
  365. }
  366. if v.user.Tier == nil {
  367. return errHTTPUnauthorized
  368. }
  369. // CHeck if we are allowed to reserve this topic
  370. if err := s.userManager.CheckAllowAccess(v.user.Name, req.Topic); err != nil {
  371. return errHTTPConflictTopicReserved
  372. }
  373. hasReservation, err := s.userManager.HasReservation(v.user.Name, req.Topic)
  374. if err != nil {
  375. return err
  376. }
  377. if !hasReservation {
  378. reservations, err := s.userManager.ReservationsCount(v.user.Name)
  379. if err != nil {
  380. return err
  381. } else if reservations >= v.user.Tier.ReservationLimit {
  382. return errHTTPTooManyRequestsLimitReservations
  383. }
  384. }
  385. // Actually add the reservation
  386. if err := s.userManager.AddReservation(v.user.Name, req.Topic, everyone); err != nil {
  387. return err
  388. }
  389. // Kill existing subscribers
  390. t, err := s.topicFromID(req.Topic)
  391. if err != nil {
  392. return err
  393. }
  394. t.CancelSubscribers(v.user.ID)
  395. return s.writeJSON(w, newSuccessResponse())
  396. }
  397. func (s *Server) handleAccountReservationDelete(w http.ResponseWriter, r *http.Request, v *visitor) error {
  398. matches := apiAccountReservationSingleRegex.FindStringSubmatch(r.URL.Path)
  399. if len(matches) != 2 {
  400. return errHTTPInternalErrorInvalidPath
  401. }
  402. topic := matches[1]
  403. if !topicRegex.MatchString(topic) {
  404. return errHTTPBadRequestTopicInvalid
  405. }
  406. authorized, err := s.userManager.HasReservation(v.user.Name, topic)
  407. if err != nil {
  408. return err
  409. } else if !authorized {
  410. return errHTTPUnauthorized
  411. }
  412. if err := s.userManager.RemoveReservations(v.user.Name, topic); err != nil {
  413. return err
  414. }
  415. return s.writeJSON(w, newSuccessResponse())
  416. }
  417. // maybeRemoveMessagesAndExcessReservations deletes topic reservations for the given user (if too many for tier),
  418. // and marks associated messages for the topics as deleted. This also eventually deletes attachments.
  419. // The process relies on the manager to perform the actual deletions (see runManager).
  420. func (s *Server) maybeRemoveMessagesAndExcessReservations(logPrefix string, u *user.User, reservationsLimit int64) error {
  421. reservations, err := s.userManager.Reservations(u.Name)
  422. if err != nil {
  423. return err
  424. } else if int64(len(reservations)) <= reservationsLimit {
  425. return nil
  426. }
  427. topics := make([]string, 0)
  428. for i := int64(len(reservations)) - 1; i >= reservationsLimit; i-- {
  429. topics = append(topics, reservations[i].Topic)
  430. }
  431. log.Info("%s Removing excess reservations for topics %s", logPrefix, strings.Join(topics, ", "))
  432. if err := s.userManager.RemoveReservations(u.Name, topics...); err != nil {
  433. return err
  434. }
  435. if err := s.messageCache.ExpireMessages(topics...); err != nil {
  436. return err
  437. }
  438. return nil
  439. }
  440. func (s *Server) publishSyncEvent(v *visitor) error {
  441. if v.user == nil || v.user.SyncTopic == "" {
  442. return nil
  443. }
  444. log.Trace("Publishing sync event to user %s's sync topic %s", v.user.Name, v.user.SyncTopic)
  445. syncTopic, err := s.topicFromID(v.user.SyncTopic)
  446. if err != nil {
  447. return err
  448. }
  449. messageBytes, err := json.Marshal(&apiAccountSyncTopicResponse{Event: syncTopicAccountSyncEvent})
  450. if err != nil {
  451. return err
  452. }
  453. m := newDefaultMessage(syncTopic.ID, string(messageBytes))
  454. if err := syncTopic.Publish(v, m); err != nil {
  455. return err
  456. }
  457. return nil
  458. }
  459. func (s *Server) publishSyncEventAsync(v *visitor) {
  460. go func() {
  461. u := v.User()
  462. if u == nil || u.SyncTopic == "" {
  463. return
  464. }
  465. if err := s.publishSyncEvent(v); err != nil {
  466. log.Trace("Error publishing to user %s's sync topic %s: %s", u.Name, u.SyncTopic, err.Error())
  467. }
  468. }()
  469. }