server_account.go 17 KB

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