server_test.go 97 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689
  1. package server
  2. import (
  3. "bufio"
  4. "context"
  5. "encoding/base64"
  6. "encoding/json"
  7. "fmt"
  8. "golang.org/x/crypto/bcrypt"
  9. "heckel.io/ntfy/user"
  10. "io"
  11. "math/rand"
  12. "net/http"
  13. "net/http/httptest"
  14. "net/netip"
  15. "os"
  16. "path/filepath"
  17. "runtime/debug"
  18. "strings"
  19. "sync"
  20. "sync/atomic"
  21. "testing"
  22. "time"
  23. "github.com/stretchr/testify/require"
  24. "heckel.io/ntfy/log"
  25. "heckel.io/ntfy/util"
  26. )
  27. func TestMain(m *testing.M) {
  28. log.SetLevel(log.ErrorLevel)
  29. os.Exit(m.Run())
  30. }
  31. func TestServer_PublishAndPoll(t *testing.T) {
  32. s := newTestServer(t, newTestConfig(t))
  33. response1 := request(t, s, "PUT", "/mytopic", "my first message", nil)
  34. msg1 := toMessage(t, response1.Body.String())
  35. require.NotEmpty(t, msg1.ID)
  36. require.Equal(t, "my first message", msg1.Message)
  37. response2 := request(t, s, "PUT", "/mytopic", "my second\n\nmessage", nil)
  38. msg2 := toMessage(t, response2.Body.String())
  39. require.NotEqual(t, msg1.ID, msg2.ID)
  40. require.NotEmpty(t, msg2.ID)
  41. require.Equal(t, "my second\n\nmessage", msg2.Message)
  42. response := request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  43. messages := toMessages(t, response.Body.String())
  44. require.Equal(t, 2, len(messages))
  45. require.Equal(t, "my first message", messages[0].Message)
  46. require.Equal(t, "my second\n\nmessage", messages[1].Message)
  47. response = request(t, s, "GET", "/mytopic/sse?poll=1&since=all", "", nil)
  48. lines := strings.Split(strings.TrimSpace(response.Body.String()), "\n")
  49. require.Equal(t, 3, len(lines))
  50. require.Equal(t, "my first message", toMessage(t, strings.TrimPrefix(lines[0], "data: ")).Message)
  51. require.Equal(t, "", lines[1])
  52. require.Equal(t, "my second\n\nmessage", toMessage(t, strings.TrimPrefix(lines[2], "data: ")).Message)
  53. response = request(t, s, "GET", "/mytopic/raw?poll=1", "", nil)
  54. lines = strings.Split(strings.TrimSpace(response.Body.String()), "\n")
  55. require.Equal(t, 2, len(lines))
  56. require.Equal(t, "my first message", lines[0])
  57. require.Equal(t, "my second message", lines[1]) // \n -> " "
  58. }
  59. func TestServer_PublishWithFirebase(t *testing.T) {
  60. sender := newTestFirebaseSender(10)
  61. s := newTestServer(t, newTestConfig(t))
  62. s.firebaseClient = newFirebaseClient(sender, &testAuther{Allow: true})
  63. response := request(t, s, "PUT", "/mytopic", "my first message", nil)
  64. msg1 := toMessage(t, response.Body.String())
  65. require.NotEmpty(t, msg1.ID)
  66. require.Equal(t, "my first message", msg1.Message)
  67. time.Sleep(100 * time.Millisecond) // Firebase publishing happens
  68. require.Equal(t, 1, len(sender.Messages()))
  69. require.Equal(t, "my first message", sender.Messages()[0].Data["message"])
  70. require.Equal(t, "my first message", sender.Messages()[0].APNS.Payload.Aps.Alert.Body)
  71. require.Equal(t, "my first message", sender.Messages()[0].APNS.Payload.CustomData["message"])
  72. }
  73. func TestServer_PublishWithFirebase_WithoutUsers_AndWithoutPanic(t *testing.T) {
  74. // This tests issue #641, which used to panic before the fix
  75. firebaseKeyFile := filepath.Join(t.TempDir(), "firebase.json")
  76. contents := `{
  77. "type": "service_account",
  78. "project_id": "ntfy-test",
  79. "private_key_id": "fsfhskjdfhskdhfskdjfhsdf",
  80. "private_key": "lalala",
  81. "client_email": "firebase-adminsdk-muv04@ntfy-test.iam.gserviceaccount.com",
  82. "client_id": "123123213",
  83. "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  84. "token_uri": "https://oauth2.googleapis.com/token",
  85. "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  86. "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-muv04%40ntfy-test.iam.gserviceaccount.com"
  87. }
  88. `
  89. require.Nil(t, os.WriteFile(firebaseKeyFile, []byte(contents), 0600))
  90. c := newTestConfig(t)
  91. c.FirebaseKeyFile = firebaseKeyFile
  92. s := newTestServer(t, c)
  93. response := request(t, s, "PUT", "/mytopic", "my first message", nil)
  94. require.Equal(t, "my first message", toMessage(t, response.Body.String()).Message)
  95. }
  96. func TestServer_SubscribeOpenAndKeepalive(t *testing.T) {
  97. t.Parallel()
  98. c := newTestConfig(t)
  99. c.KeepaliveInterval = time.Second
  100. s := newTestServer(t, c)
  101. rr := httptest.NewRecorder()
  102. ctx, cancel := context.WithCancel(context.Background())
  103. req, err := http.NewRequestWithContext(ctx, "GET", "/mytopic/json", nil)
  104. if err != nil {
  105. t.Fatal(err)
  106. }
  107. doneChan := make(chan bool)
  108. go func() {
  109. s.handle(rr, req)
  110. doneChan <- true
  111. }()
  112. time.Sleep(1300 * time.Millisecond)
  113. cancel()
  114. <-doneChan
  115. messages := toMessages(t, rr.Body.String())
  116. require.Equal(t, 2, len(messages))
  117. require.Equal(t, openEvent, messages[0].Event)
  118. require.Equal(t, "mytopic", messages[0].Topic)
  119. require.Equal(t, "", messages[0].Message)
  120. require.Equal(t, "", messages[0].Title)
  121. require.Equal(t, 0, messages[0].Priority)
  122. require.Nil(t, messages[0].Tags)
  123. require.Equal(t, keepaliveEvent, messages[1].Event)
  124. require.Equal(t, "mytopic", messages[1].Topic)
  125. require.Equal(t, "", messages[1].Message)
  126. require.Equal(t, "", messages[1].Title)
  127. require.Equal(t, 0, messages[1].Priority)
  128. require.Nil(t, messages[1].Tags)
  129. }
  130. func TestServer_PublishAndSubscribe(t *testing.T) {
  131. t.Parallel()
  132. s := newTestServer(t, newTestConfig(t))
  133. subscribeRR := httptest.NewRecorder()
  134. subscribeCancel := subscribe(t, s, "/mytopic/json", subscribeRR)
  135. publishFirstRR := request(t, s, "PUT", "/mytopic", "my first message", nil)
  136. require.Equal(t, 200, publishFirstRR.Code)
  137. time.Sleep(500 * time.Millisecond) // Publishing is done asynchronously, this avoids races
  138. publishSecondRR := request(t, s, "PUT", "/mytopic", "my other message", map[string]string{
  139. "Title": " This is a title ",
  140. "X-Tags": "tag1,tag 2, tag3",
  141. "p": "1",
  142. })
  143. require.Equal(t, 200, publishSecondRR.Code)
  144. subscribeCancel()
  145. messages := toMessages(t, subscribeRR.Body.String())
  146. require.Equal(t, 3, len(messages))
  147. require.Equal(t, openEvent, messages[0].Event)
  148. require.Equal(t, messageEvent, messages[1].Event)
  149. require.Equal(t, "mytopic", messages[1].Topic)
  150. require.Equal(t, "my first message", messages[1].Message)
  151. require.Equal(t, "", messages[1].Title)
  152. require.Equal(t, 0, messages[1].Priority)
  153. require.Nil(t, messages[1].Tags)
  154. require.True(t, time.Now().Add(12*time.Hour-5*time.Second).Unix() < messages[1].Expires)
  155. require.True(t, time.Now().Add(12*time.Hour+5*time.Second).Unix() > messages[1].Expires)
  156. require.Equal(t, messageEvent, messages[2].Event)
  157. require.Equal(t, "mytopic", messages[2].Topic)
  158. require.Equal(t, "my other message", messages[2].Message)
  159. require.Equal(t, "This is a title", messages[2].Title)
  160. require.Equal(t, 1, messages[2].Priority)
  161. require.Equal(t, []string{"tag1", "tag 2", "tag3"}, messages[2].Tags)
  162. }
  163. func TestServer_Publish_Disallowed_Topic(t *testing.T) {
  164. c := newTestConfig(t)
  165. c.DisallowedTopics = []string{"about", "time", "this", "got", "added"}
  166. s := newTestServer(t, c)
  167. rr := request(t, s, "PUT", "/mytopic", "my first message", nil)
  168. require.Equal(t, 200, rr.Code)
  169. rr = request(t, s, "PUT", "/about", "another message", nil)
  170. require.Equal(t, 400, rr.Code)
  171. require.Equal(t, 40010, toHTTPError(t, rr.Body.String()).Code)
  172. }
  173. func TestServer_StaticSites(t *testing.T) {
  174. s := newTestServer(t, newTestConfig(t))
  175. rr := request(t, s, "GET", "/", "", nil)
  176. require.Equal(t, 200, rr.Code)
  177. require.Contains(t, rr.Body.String(), "</html>")
  178. rr = request(t, s, "HEAD", "/", "", nil)
  179. require.Equal(t, 200, rr.Code)
  180. rr = request(t, s, "OPTIONS", "/", "", nil)
  181. require.Equal(t, 200, rr.Code)
  182. rr = request(t, s, "GET", "/does-not-exist.txt", "", nil)
  183. require.Equal(t, 404, rr.Code)
  184. rr = request(t, s, "GET", "/mytopic", "", nil)
  185. require.Equal(t, 200, rr.Code)
  186. require.Contains(t, rr.Body.String(), `<meta name="robots" content="noindex, nofollow" />`)
  187. rr = request(t, s, "GET", "/docs", "", nil)
  188. require.Equal(t, 301, rr.Code)
  189. // Docs test removed, it was failing annoyingly.
  190. }
  191. func TestServer_WebEnabled(t *testing.T) {
  192. conf := newTestConfig(t)
  193. conf.WebRoot = "" // Disable web app
  194. s := newTestServer(t, conf)
  195. rr := request(t, s, "GET", "/", "", nil)
  196. require.Equal(t, 404, rr.Code)
  197. rr = request(t, s, "GET", "/config.js", "", nil)
  198. require.Equal(t, 404, rr.Code)
  199. rr = request(t, s, "GET", "/static/css/home.css", "", nil)
  200. require.Equal(t, 404, rr.Code)
  201. conf2 := newTestConfig(t)
  202. conf2.WebRoot = "/"
  203. s2 := newTestServer(t, conf2)
  204. rr = request(t, s2, "GET", "/", "", nil)
  205. require.Equal(t, 200, rr.Code)
  206. rr = request(t, s2, "GET", "/config.js", "", nil)
  207. require.Equal(t, 200, rr.Code)
  208. }
  209. func TestServer_PublishLargeMessage(t *testing.T) {
  210. c := newTestConfig(t)
  211. c.AttachmentCacheDir = "" // Disable attachments
  212. s := newTestServer(t, c)
  213. body := strings.Repeat("this is a large message", 5000)
  214. response := request(t, s, "PUT", "/mytopic", body, nil)
  215. require.Equal(t, 400, response.Code)
  216. }
  217. func TestServer_PublishPriority(t *testing.T) {
  218. s := newTestServer(t, newTestConfig(t))
  219. for prio := 1; prio <= 5; prio++ {
  220. response := request(t, s, "GET", fmt.Sprintf("/mytopic/publish?priority=%d", prio), fmt.Sprintf("priority %d", prio), nil)
  221. msg := toMessage(t, response.Body.String())
  222. require.Equal(t, prio, msg.Priority)
  223. }
  224. response := request(t, s, "GET", "/mytopic/publish?priority=min", "test", nil)
  225. require.Equal(t, 1, toMessage(t, response.Body.String()).Priority)
  226. response = request(t, s, "GET", "/mytopic/send?priority=low", "test", nil)
  227. require.Equal(t, 2, toMessage(t, response.Body.String()).Priority)
  228. response = request(t, s, "GET", "/mytopic/send?priority=default", "test", nil)
  229. require.Equal(t, 3, toMessage(t, response.Body.String()).Priority)
  230. response = request(t, s, "GET", "/mytopic/send?priority=high", "test", nil)
  231. require.Equal(t, 4, toMessage(t, response.Body.String()).Priority)
  232. response = request(t, s, "GET", "/mytopic/send?priority=max", "test", nil)
  233. require.Equal(t, 5, toMessage(t, response.Body.String()).Priority)
  234. response = request(t, s, "GET", "/mytopic/trigger?priority=urgent", "test", nil)
  235. require.Equal(t, 5, toMessage(t, response.Body.String()).Priority)
  236. response = request(t, s, "GET", "/mytopic/trigger?priority=INVALID", "test", nil)
  237. require.Equal(t, 40007, toHTTPError(t, response.Body.String()).Code)
  238. }
  239. func TestServer_PublishGETOnlyOneTopic(t *testing.T) {
  240. // This tests a bug that allowed publishing topics with a comma in the name (no ticket)
  241. s := newTestServer(t, newTestConfig(t))
  242. response := request(t, s, "GET", "/mytopic,mytopic2/publish?m=hi", "", nil)
  243. require.Equal(t, 404, response.Code)
  244. }
  245. func TestServer_PublishNoCache(t *testing.T) {
  246. s := newTestServer(t, newTestConfig(t))
  247. response := request(t, s, "PUT", "/mytopic", "this message is not cached", map[string]string{
  248. "Cache": "no",
  249. })
  250. msg := toMessage(t, response.Body.String())
  251. require.NotEmpty(t, msg.ID)
  252. require.Equal(t, "this message is not cached", msg.Message)
  253. require.Equal(t, int64(0), msg.Expires)
  254. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  255. messages := toMessages(t, response.Body.String())
  256. require.Empty(t, messages)
  257. }
  258. func TestServer_PublishAt(t *testing.T) {
  259. t.Parallel()
  260. s := newTestServer(t, newTestConfig(t))
  261. response := request(t, s, "PUT", "/mytopic", "a message", map[string]string{
  262. "In": "1h",
  263. })
  264. require.Equal(t, 200, response.Code)
  265. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  266. messages := toMessages(t, response.Body.String())
  267. require.Equal(t, 0, len(messages))
  268. // Update message time to the past
  269. fakeTime := time.Now().Add(-10 * time.Second).Unix()
  270. _, err := s.messageCache.db.Exec(`UPDATE messages SET time=?`, fakeTime)
  271. require.Nil(t, err)
  272. // Trigger delayed message sending
  273. require.Nil(t, s.sendDelayedMessages())
  274. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  275. messages = toMessages(t, response.Body.String())
  276. require.Equal(t, 1, len(messages))
  277. require.Equal(t, "a message", messages[0].Message)
  278. require.Equal(t, netip.Addr{}, messages[0].Sender) // Never return the sender!
  279. messages, err = s.messageCache.Messages("mytopic", sinceAllMessages, true)
  280. require.Nil(t, err)
  281. require.Equal(t, 1, len(messages))
  282. require.Equal(t, "a message", messages[0].Message)
  283. require.Equal(t, "9.9.9.9", messages[0].Sender.String()) // It's stored in the DB though!
  284. }
  285. func TestServer_PublishAt_FromUser(t *testing.T) {
  286. t.Parallel()
  287. s := newTestServer(t, newTestConfigWithAuthFile(t))
  288. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleAdmin))
  289. response := request(t, s, "PUT", "/mytopic", "a message", map[string]string{
  290. "Authorization": util.BasicAuth("phil", "phil"),
  291. "In": "1h",
  292. })
  293. require.Equal(t, 200, response.Code)
  294. // Message doesn't show up immediately
  295. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  296. messages := toMessages(t, response.Body.String())
  297. require.Equal(t, 0, len(messages))
  298. // Update message time to the past
  299. fakeTime := time.Now().Add(-10 * time.Second).Unix()
  300. _, err := s.messageCache.db.Exec(`UPDATE messages SET time=?`, fakeTime)
  301. require.Nil(t, err)
  302. // Trigger delayed message sending
  303. require.Nil(t, s.sendDelayedMessages())
  304. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  305. messages = toMessages(t, response.Body.String())
  306. require.Equal(t, 1, len(messages))
  307. require.Equal(t, fakeTime, messages[0].Time)
  308. require.Equal(t, "a message", messages[0].Message)
  309. messages, err = s.messageCache.Messages("mytopic", sinceAllMessages, true)
  310. require.Nil(t, err)
  311. require.Equal(t, 1, len(messages))
  312. require.Equal(t, "a message", messages[0].Message)
  313. require.True(t, strings.HasPrefix(messages[0].User, "u_"))
  314. }
  315. func TestServer_PublishAt_Expires(t *testing.T) {
  316. s := newTestServer(t, newTestConfig(t))
  317. response := request(t, s, "PUT", "/mytopic", "a message", map[string]string{
  318. "In": "2 days",
  319. })
  320. require.Equal(t, 200, response.Code)
  321. m := toMessage(t, response.Body.String())
  322. require.True(t, m.Expires > time.Now().Add(12*time.Hour+48*time.Hour-time.Minute).Unix())
  323. require.True(t, m.Expires < time.Now().Add(12*time.Hour+48*time.Hour+time.Minute).Unix())
  324. }
  325. func TestServer_PublishAtWithCacheError(t *testing.T) {
  326. s := newTestServer(t, newTestConfig(t))
  327. response := request(t, s, "PUT", "/mytopic", "a message", map[string]string{
  328. "Cache": "no",
  329. "In": "30 min",
  330. })
  331. require.Equal(t, 400, response.Code)
  332. require.Equal(t, errHTTPBadRequestDelayNoCache, toHTTPError(t, response.Body.String()))
  333. }
  334. func TestServer_PublishAtTooShortDelay(t *testing.T) {
  335. s := newTestServer(t, newTestConfig(t))
  336. response := request(t, s, "PUT", "/mytopic", "a message", map[string]string{
  337. "In": "1s",
  338. })
  339. require.Equal(t, 400, response.Code)
  340. }
  341. func TestServer_PublishAtTooLongDelay(t *testing.T) {
  342. s := newTestServer(t, newTestConfig(t))
  343. response := request(t, s, "PUT", "/mytopic", "a message", map[string]string{
  344. "In": "99999999h",
  345. })
  346. require.Equal(t, 400, response.Code)
  347. }
  348. func TestServer_PublishAtInvalidDelay(t *testing.T) {
  349. s := newTestServer(t, newTestConfig(t))
  350. response := request(t, s, "PUT", "/mytopic?delay=INVALID", "a message", nil)
  351. err := toHTTPError(t, response.Body.String())
  352. require.Equal(t, 400, response.Code)
  353. require.Equal(t, 40004, err.Code)
  354. }
  355. func TestServer_PublishAtTooLarge(t *testing.T) {
  356. s := newTestServer(t, newTestConfig(t))
  357. response := request(t, s, "PUT", "/mytopic?x-in=99999h", "a message", nil)
  358. err := toHTTPError(t, response.Body.String())
  359. require.Equal(t, 400, response.Code)
  360. require.Equal(t, 40006, err.Code)
  361. }
  362. func TestServer_PublishAtAndPrune(t *testing.T) {
  363. s := newTestServer(t, newTestConfig(t))
  364. response := request(t, s, "PUT", "/mytopic", "a message", map[string]string{
  365. "In": "1h",
  366. })
  367. require.Equal(t, 200, response.Code)
  368. s.execManager() // Fire pruning
  369. response = request(t, s, "GET", "/mytopic/json?poll=1&scheduled=1", "", nil)
  370. messages := toMessages(t, response.Body.String())
  371. require.Equal(t, 1, len(messages)) // Not affected by pruning
  372. require.Equal(t, "a message", messages[0].Message)
  373. }
  374. func TestServer_PublishAndMultiPoll(t *testing.T) {
  375. s := newTestServer(t, newTestConfig(t))
  376. response := request(t, s, "PUT", "/mytopic1", "message 1", nil)
  377. msg := toMessage(t, response.Body.String())
  378. require.NotEmpty(t, msg.ID)
  379. require.Equal(t, "mytopic1", msg.Topic)
  380. require.Equal(t, "message 1", msg.Message)
  381. response = request(t, s, "PUT", "/mytopic2", "message 2", nil)
  382. msg = toMessage(t, response.Body.String())
  383. require.NotEmpty(t, msg.ID)
  384. require.Equal(t, "mytopic2", msg.Topic)
  385. require.Equal(t, "message 2", msg.Message)
  386. response = request(t, s, "GET", "/mytopic1/json?poll=1", "", nil)
  387. messages := toMessages(t, response.Body.String())
  388. require.Equal(t, 1, len(messages))
  389. require.Equal(t, "mytopic1", messages[0].Topic)
  390. require.Equal(t, "message 1", messages[0].Message)
  391. response = request(t, s, "GET", "/mytopic1,mytopic2/json?poll=1", "", nil)
  392. messages = toMessages(t, response.Body.String())
  393. require.Equal(t, 2, len(messages))
  394. require.Equal(t, "mytopic1", messages[0].Topic)
  395. require.Equal(t, "message 1", messages[0].Message)
  396. require.Equal(t, "mytopic2", messages[1].Topic)
  397. require.Equal(t, "message 2", messages[1].Message)
  398. }
  399. func TestServer_PublishWithNopCache(t *testing.T) {
  400. c := newTestConfig(t)
  401. c.CacheDuration = 0
  402. s := newTestServer(t, c)
  403. subscribeRR := httptest.NewRecorder()
  404. subscribeCancel := subscribe(t, s, "/mytopic/json", subscribeRR)
  405. publishRR := request(t, s, "PUT", "/mytopic", "my first message", nil)
  406. require.Equal(t, 200, publishRR.Code)
  407. subscribeCancel()
  408. messages := toMessages(t, subscribeRR.Body.String())
  409. require.Equal(t, 2, len(messages))
  410. require.Equal(t, openEvent, messages[0].Event)
  411. require.Equal(t, messageEvent, messages[1].Event)
  412. require.Equal(t, "my first message", messages[1].Message)
  413. response := request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  414. messages = toMessages(t, response.Body.String())
  415. require.Empty(t, messages)
  416. }
  417. func TestServer_PublishAndPollSince(t *testing.T) {
  418. t.Parallel()
  419. s := newTestServer(t, newTestConfig(t))
  420. request(t, s, "PUT", "/mytopic", "test 1", nil)
  421. time.Sleep(1100 * time.Millisecond)
  422. since := time.Now().Unix()
  423. request(t, s, "PUT", "/mytopic", "test 2", nil)
  424. response := request(t, s, "GET", fmt.Sprintf("/mytopic/json?poll=1&since=%d", since), "", nil)
  425. messages := toMessages(t, response.Body.String())
  426. require.Equal(t, 1, len(messages))
  427. require.Equal(t, "test 2", messages[0].Message)
  428. response = request(t, s, "GET", "/mytopic/json?poll=1&since=10s", "", nil)
  429. messages = toMessages(t, response.Body.String())
  430. require.Equal(t, 2, len(messages))
  431. require.Equal(t, "test 1", messages[0].Message)
  432. response = request(t, s, "GET", "/mytopic/json?poll=1&since=100ms", "", nil)
  433. messages = toMessages(t, response.Body.String())
  434. require.Equal(t, 1, len(messages))
  435. require.Equal(t, "test 2", messages[0].Message)
  436. response = request(t, s, "GET", "/mytopic/json?poll=1&since=INVALID", "", nil)
  437. require.Equal(t, 40008, toHTTPError(t, response.Body.String()).Code)
  438. }
  439. func newMessageWithTimestamp(topic, message string, timestamp int64) *message {
  440. m := newDefaultMessage(topic, message)
  441. m.Time = timestamp
  442. return m
  443. }
  444. func TestServer_PollSinceID_MultipleTopics(t *testing.T) {
  445. s := newTestServer(t, newTestConfig(t))
  446. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic1", "test 1", 1655740277)))
  447. markerMessage := newMessageWithTimestamp("mytopic2", "test 2", 1655740283)
  448. require.Nil(t, s.messageCache.AddMessage(markerMessage))
  449. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic1", "test 3", 1655740289)))
  450. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic2", "test 4", 1655740293)))
  451. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic1", "test 5", 1655740297)))
  452. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic2", "test 6", 1655740303)))
  453. response := request(t, s, "GET", fmt.Sprintf("/mytopic1,mytopic2/json?poll=1&since=%s", markerMessage.ID), "", nil)
  454. messages := toMessages(t, response.Body.String())
  455. require.Equal(t, 4, len(messages))
  456. require.Equal(t, "test 3", messages[0].Message)
  457. require.Equal(t, "mytopic1", messages[0].Topic)
  458. require.Equal(t, "test 4", messages[1].Message)
  459. require.Equal(t, "mytopic2", messages[1].Topic)
  460. require.Equal(t, "test 5", messages[2].Message)
  461. require.Equal(t, "mytopic1", messages[2].Topic)
  462. require.Equal(t, "test 6", messages[3].Message)
  463. require.Equal(t, "mytopic2", messages[3].Topic)
  464. }
  465. func TestServer_PollSinceID_MultipleTopics_IDDoesNotMatch(t *testing.T) {
  466. s := newTestServer(t, newTestConfig(t))
  467. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic1", "test 3", 1655740289)))
  468. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic2", "test 4", 1655740293)))
  469. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic1", "test 5", 1655740297)))
  470. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic2", "test 6", 1655740303)))
  471. response := request(t, s, "GET", "/mytopic1,mytopic2/json?poll=1&since=NoMatchForID", "", nil)
  472. messages := toMessages(t, response.Body.String())
  473. require.Equal(t, 4, len(messages))
  474. require.Equal(t, "test 3", messages[0].Message)
  475. require.Equal(t, "test 4", messages[1].Message)
  476. require.Equal(t, "test 5", messages[2].Message)
  477. require.Equal(t, "test 6", messages[3].Message)
  478. }
  479. func TestServer_PublishViaGET(t *testing.T) {
  480. s := newTestServer(t, newTestConfig(t))
  481. response := request(t, s, "GET", "/mytopic/trigger", "", nil)
  482. msg := toMessage(t, response.Body.String())
  483. require.NotEmpty(t, msg.ID)
  484. require.Equal(t, "triggered", msg.Message)
  485. response = request(t, s, "GET", "/mytopic/send?message=This+is+a+test&t=This+is+a+title&tags=skull&x-priority=5&delay=24h", "", nil)
  486. msg = toMessage(t, response.Body.String())
  487. require.NotEmpty(t, msg.ID)
  488. require.Equal(t, "This is a test", msg.Message)
  489. require.Equal(t, "This is a title", msg.Title)
  490. require.Equal(t, []string{"skull"}, msg.Tags)
  491. require.Equal(t, 5, msg.Priority)
  492. require.Greater(t, msg.Time, time.Now().Add(23*time.Hour).Unix())
  493. }
  494. func TestServer_PublishMessageInHeaderWithNewlines(t *testing.T) {
  495. s := newTestServer(t, newTestConfig(t))
  496. response := request(t, s, "PUT", "/mytopic", "", map[string]string{
  497. "Message": "Line 1\\nLine 2",
  498. })
  499. msg := toMessage(t, response.Body.String())
  500. require.NotEmpty(t, msg.ID)
  501. require.Equal(t, "Line 1\nLine 2", msg.Message) // \\n -> \n !
  502. }
  503. func TestServer_PublishInvalidTopic(t *testing.T) {
  504. s := newTestServer(t, newTestConfig(t))
  505. s.smtpSender = &testMailer{}
  506. response := request(t, s, "PUT", "/docs", "fail", nil)
  507. require.Equal(t, 40010, toHTTPError(t, response.Body.String()).Code)
  508. }
  509. func TestServer_PollWithQueryFilters(t *testing.T) {
  510. s := newTestServer(t, newTestConfig(t))
  511. response := request(t, s, "PUT", "/mytopic?priority=1&tags=tag1,tag2", "my first message", nil)
  512. msg := toMessage(t, response.Body.String())
  513. require.NotEmpty(t, msg.ID)
  514. response = request(t, s, "PUT", "/mytopic?title=a+title", "my second message", map[string]string{
  515. "Tags": "tag2,tag3",
  516. })
  517. msg = toMessage(t, response.Body.String())
  518. require.NotEmpty(t, msg.ID)
  519. queriesThatShouldReturnMessageOne := []string{
  520. "/mytopic/json?poll=1&priority=1",
  521. "/mytopic/json?poll=1&priority=min",
  522. "/mytopic/json?poll=1&priority=min,low",
  523. "/mytopic/json?poll=1&priority=1,2",
  524. "/mytopic/json?poll=1&p=2,min",
  525. "/mytopic/json?poll=1&tags=tag1",
  526. "/mytopic/json?poll=1&tags=tag1,tag2",
  527. "/mytopic/json?poll=1&message=my+first+message",
  528. }
  529. for _, query := range queriesThatShouldReturnMessageOne {
  530. response = request(t, s, "GET", query, "", nil)
  531. messages := toMessages(t, response.Body.String())
  532. require.Equal(t, 1, len(messages), "Query failed: "+query)
  533. require.Equal(t, "my first message", messages[0].Message, "Query failed: "+query)
  534. }
  535. queriesThatShouldReturnMessageTwo := []string{
  536. "/mytopic/json?poll=1&x-priority=3", // !
  537. "/mytopic/json?poll=1&priority=3",
  538. "/mytopic/json?poll=1&priority=default",
  539. "/mytopic/json?poll=1&p=3",
  540. "/mytopic/json?poll=1&x-tags=tag2,tag3",
  541. "/mytopic/json?poll=1&tags=tag2,tag3",
  542. "/mytopic/json?poll=1&tag=tag2,tag3",
  543. "/mytopic/json?poll=1&ta=tag2,tag3",
  544. "/mytopic/json?poll=1&x-title=a+title",
  545. "/mytopic/json?poll=1&title=a+title",
  546. "/mytopic/json?poll=1&t=a+title",
  547. "/mytopic/json?poll=1&x-message=my+second+message",
  548. "/mytopic/json?poll=1&message=my+second+message",
  549. "/mytopic/json?poll=1&m=my+second+message",
  550. "/mytopic/json?x-poll=1&m=my+second+message",
  551. "/mytopic/json?po=1&m=my+second+message",
  552. }
  553. for _, query := range queriesThatShouldReturnMessageTwo {
  554. response = request(t, s, "GET", query, "", nil)
  555. messages := toMessages(t, response.Body.String())
  556. require.Equal(t, 1, len(messages), "Query failed: "+query)
  557. require.Equal(t, "my second message", messages[0].Message, "Query failed: "+query)
  558. }
  559. queriesThatShouldReturnNoMessages := []string{
  560. "/mytopic/json?poll=1&priority=4",
  561. "/mytopic/json?poll=1&tags=tag1,tag2,tag3",
  562. "/mytopic/json?poll=1&title=another+title",
  563. "/mytopic/json?poll=1&message=my+third+message",
  564. "/mytopic/json?poll=1&message=my+third+message",
  565. }
  566. for _, query := range queriesThatShouldReturnNoMessages {
  567. response = request(t, s, "GET", query, "", nil)
  568. messages := toMessages(t, response.Body.String())
  569. require.Equal(t, 0, len(messages), "Query failed: "+query)
  570. }
  571. }
  572. func TestServer_SubscribeWithQueryFilters(t *testing.T) {
  573. t.Parallel()
  574. c := newTestConfig(t)
  575. c.KeepaliveInterval = 800 * time.Millisecond
  576. s := newTestServer(t, c)
  577. subscribeResponse := httptest.NewRecorder()
  578. subscribeCancel := subscribe(t, s, "/mytopic/json?tags=zfs-issue", subscribeResponse)
  579. response := request(t, s, "PUT", "/mytopic", "my first message", nil)
  580. require.Equal(t, 200, response.Code)
  581. response = request(t, s, "PUT", "/mytopic", "ZFS scrub failed", map[string]string{
  582. "Tags": "zfs-issue,zfs-scrub",
  583. })
  584. require.Equal(t, 200, response.Code)
  585. time.Sleep(850 * time.Millisecond)
  586. subscribeCancel()
  587. messages := toMessages(t, subscribeResponse.Body.String())
  588. require.Equal(t, 3, len(messages))
  589. require.Equal(t, openEvent, messages[0].Event)
  590. require.Equal(t, messageEvent, messages[1].Event)
  591. require.Equal(t, "ZFS scrub failed", messages[1].Message)
  592. require.Equal(t, keepaliveEvent, messages[2].Event)
  593. }
  594. func TestServer_Auth_Success_Admin(t *testing.T) {
  595. c := newTestConfigWithAuthFile(t)
  596. s := newTestServer(t, c)
  597. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleAdmin))
  598. response := request(t, s, "GET", "/mytopic/auth", "", map[string]string{
  599. "Authorization": util.BasicAuth("phil", "phil"),
  600. })
  601. require.Equal(t, 200, response.Code)
  602. require.Equal(t, `{"success":true}`+"\n", response.Body.String())
  603. }
  604. func TestServer_Auth_Success_User(t *testing.T) {
  605. c := newTestConfigWithAuthFile(t)
  606. c.AuthDefault = user.PermissionDenyAll
  607. s := newTestServer(t, c)
  608. require.Nil(t, s.userManager.AddUser("ben", "ben", user.RoleUser))
  609. require.Nil(t, s.userManager.AllowAccess("ben", "mytopic", user.PermissionReadWrite))
  610. response := request(t, s, "GET", "/mytopic/auth", "", map[string]string{
  611. "Authorization": util.BasicAuth("ben", "ben"),
  612. })
  613. require.Equal(t, 200, response.Code)
  614. }
  615. func TestServer_Auth_Success_User_MultipleTopics(t *testing.T) {
  616. c := newTestConfigWithAuthFile(t)
  617. c.AuthDefault = user.PermissionDenyAll
  618. s := newTestServer(t, c)
  619. require.Nil(t, s.userManager.AddUser("ben", "ben", user.RoleUser))
  620. require.Nil(t, s.userManager.AllowAccess("ben", "mytopic", user.PermissionReadWrite))
  621. require.Nil(t, s.userManager.AllowAccess("ben", "anothertopic", user.PermissionReadWrite))
  622. response := request(t, s, "GET", "/mytopic,anothertopic/auth", "", map[string]string{
  623. "Authorization": util.BasicAuth("ben", "ben"),
  624. })
  625. require.Equal(t, 200, response.Code)
  626. response = request(t, s, "GET", "/mytopic,anothertopic,NOT-THIS-ONE/auth", "", map[string]string{
  627. "Authorization": util.BasicAuth("ben", "ben"),
  628. })
  629. require.Equal(t, 403, response.Code)
  630. }
  631. func TestServer_Auth_Fail_InvalidPass(t *testing.T) {
  632. c := newTestConfig(t)
  633. c.AuthFile = filepath.Join(t.TempDir(), "user.db")
  634. c.AuthDefault = user.PermissionDenyAll
  635. s := newTestServer(t, c)
  636. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleAdmin))
  637. response := request(t, s, "GET", "/mytopic/auth", "", map[string]string{
  638. "Authorization": util.BasicAuth("phil", "INVALID"),
  639. })
  640. require.Equal(t, 401, response.Code)
  641. }
  642. func TestServer_Auth_Fail_Unauthorized(t *testing.T) {
  643. c := newTestConfigWithAuthFile(t)
  644. c.AuthDefault = user.PermissionDenyAll
  645. s := newTestServer(t, c)
  646. require.Nil(t, s.userManager.AddUser("ben", "ben", user.RoleUser))
  647. require.Nil(t, s.userManager.AllowAccess("ben", "sometopic", user.PermissionReadWrite)) // Not mytopic!
  648. response := request(t, s, "GET", "/mytopic/auth", "", map[string]string{
  649. "Authorization": util.BasicAuth("ben", "ben"),
  650. })
  651. require.Equal(t, 403, response.Code)
  652. }
  653. func TestServer_Auth_Fail_CannotPublish(t *testing.T) {
  654. c := newTestConfigWithAuthFile(t)
  655. c.AuthDefault = user.PermissionReadWrite // Open by default
  656. s := newTestServer(t, c)
  657. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleAdmin))
  658. require.Nil(t, s.userManager.AllowAccess(user.Everyone, "private", user.PermissionDenyAll))
  659. require.Nil(t, s.userManager.AllowAccess(user.Everyone, "announcements", user.PermissionRead))
  660. response := request(t, s, "PUT", "/mytopic", "test", nil)
  661. require.Equal(t, 200, response.Code)
  662. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  663. require.Equal(t, 200, response.Code)
  664. response = request(t, s, "PUT", "/announcements", "test", nil)
  665. require.Equal(t, 403, response.Code) // Cannot write as anonymous
  666. response = request(t, s, "PUT", "/announcements", "test", map[string]string{
  667. "Authorization": util.BasicAuth("phil", "phil"),
  668. })
  669. require.Equal(t, 200, response.Code)
  670. response = request(t, s, "GET", "/announcements/json?poll=1", "", nil)
  671. require.Equal(t, 200, response.Code) // Anonymous read allowed
  672. response = request(t, s, "GET", "/private/json?poll=1", "", nil)
  673. require.Equal(t, 403, response.Code) // Anonymous read not allowed
  674. }
  675. func TestServer_Auth_Fail_Rate_Limiting(t *testing.T) {
  676. c := newTestConfigWithAuthFile(t)
  677. c.VisitorAuthFailureLimitBurst = 10
  678. s := newTestServer(t, c)
  679. for i := 0; i < 10; i++ {
  680. response := request(t, s, "PUT", "/announcements", "test", map[string]string{
  681. "Authorization": util.BasicAuth("phil", "phil"),
  682. })
  683. require.Equal(t, 401, response.Code)
  684. }
  685. response := request(t, s, "PUT", "/announcements", "test", map[string]string{
  686. "Authorization": util.BasicAuth("phil", "phil"),
  687. })
  688. require.Equal(t, 429, response.Code)
  689. require.Equal(t, 42909, toHTTPError(t, response.Body.String()).Code)
  690. }
  691. func TestServer_Auth_ViaQuery(t *testing.T) {
  692. c := newTestConfigWithAuthFile(t)
  693. c.AuthDefault = user.PermissionDenyAll
  694. s := newTestServer(t, c)
  695. require.Nil(t, s.userManager.AddUser("ben", "some pass", user.RoleAdmin))
  696. u := fmt.Sprintf("/mytopic/json?poll=1&auth=%s", base64.RawURLEncoding.EncodeToString([]byte(util.BasicAuth("ben", "some pass"))))
  697. response := request(t, s, "GET", u, "", nil)
  698. require.Equal(t, 200, response.Code)
  699. u = fmt.Sprintf("/mytopic/json?poll=1&auth=%s", base64.RawURLEncoding.EncodeToString([]byte(util.BasicAuth("ben", "WRONNNGGGG"))))
  700. response = request(t, s, "GET", u, "", nil)
  701. require.Equal(t, 401, response.Code)
  702. }
  703. func TestServer_Auth_NonBasicHeader(t *testing.T) {
  704. s := newTestServer(t, newTestConfigWithAuthFile(t))
  705. response := request(t, s, "PUT", "/mytopic", "test", map[string]string{
  706. "Authorization": "WebPush not-supported",
  707. })
  708. require.Equal(t, 200, response.Code)
  709. response = request(t, s, "PUT", "/mytopic", "test", map[string]string{
  710. "Authorization": "Bearer supported",
  711. })
  712. require.Equal(t, 401, response.Code)
  713. response = request(t, s, "PUT", "/mytopic", "test", map[string]string{
  714. "Authorization": "basic supported",
  715. })
  716. require.Equal(t, 401, response.Code)
  717. }
  718. func TestServer_StatsResetter(t *testing.T) {
  719. t.Parallel()
  720. // This tests the stats resetter for
  721. // - an anonymous user
  722. // - a user without a tier (treated like the same as the anonymous user)
  723. // - a user with a tier
  724. c := newTestConfigWithAuthFile(t)
  725. c.VisitorStatsResetTime = time.Now().Add(2 * time.Second)
  726. s := newTestServer(t, c)
  727. go s.runStatsResetter()
  728. // Create user with tier (tieruser) and user without tier (phil)
  729. require.Nil(t, s.userManager.AddTier(&user.Tier{
  730. Code: "test",
  731. MessageLimit: 5,
  732. MessageExpiryDuration: -5 * time.Second, // Second, what a hack!
  733. }))
  734. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser))
  735. require.Nil(t, s.userManager.AddUser("tieruser", "tieruser", user.RoleUser))
  736. require.Nil(t, s.userManager.ChangeTier("tieruser", "test"))
  737. // Send an anonymous message
  738. response := request(t, s, "PUT", "/mytopic", "test", nil)
  739. require.Equal(t, 200, response.Code)
  740. // Send messages from user without tier (phil)
  741. for i := 0; i < 5; i++ {
  742. response := request(t, s, "PUT", "/mytopic", "test", map[string]string{
  743. "Authorization": util.BasicAuth("phil", "phil"),
  744. })
  745. require.Equal(t, 200, response.Code)
  746. }
  747. // Send messages from user with tier
  748. for i := 0; i < 2; i++ {
  749. response := request(t, s, "PUT", "/mytopic", "test", map[string]string{
  750. "Authorization": util.BasicAuth("tieruser", "tieruser"),
  751. })
  752. require.Equal(t, 200, response.Code)
  753. }
  754. // User stats show 6 messages (for user without tier)
  755. response = request(t, s, "GET", "/v1/account", "", map[string]string{
  756. "Authorization": util.BasicAuth("phil", "phil"),
  757. })
  758. require.Equal(t, 200, response.Code)
  759. account, err := util.UnmarshalJSON[apiAccountResponse](io.NopCloser(response.Body))
  760. require.Nil(t, err)
  761. require.Equal(t, int64(6), account.Stats.Messages)
  762. // User stats show 6 messages (for anonymous visitor)
  763. response = request(t, s, "GET", "/v1/account", "", nil)
  764. require.Equal(t, 200, response.Code)
  765. account, err = util.UnmarshalJSON[apiAccountResponse](io.NopCloser(response.Body))
  766. require.Nil(t, err)
  767. require.Equal(t, int64(6), account.Stats.Messages)
  768. // User stats show 2 messages (for user with tier)
  769. response = request(t, s, "GET", "/v1/account", "", map[string]string{
  770. "Authorization": util.BasicAuth("tieruser", "tieruser"),
  771. })
  772. require.Equal(t, 200, response.Code)
  773. account, err = util.UnmarshalJSON[apiAccountResponse](io.NopCloser(response.Body))
  774. require.Nil(t, err)
  775. require.Equal(t, int64(2), account.Stats.Messages)
  776. // Wait for stats resetter to run
  777. waitFor(t, func() bool {
  778. response = request(t, s, "GET", "/v1/account", "", map[string]string{
  779. "Authorization": util.BasicAuth("phil", "phil"),
  780. })
  781. require.Equal(t, 200, response.Code)
  782. account, err = util.UnmarshalJSON[apiAccountResponse](io.NopCloser(response.Body))
  783. require.Nil(t, err)
  784. return account.Stats.Messages == 0
  785. })
  786. // User stats show 0 messages now!
  787. response = request(t, s, "GET", "/v1/account", "", map[string]string{
  788. "Authorization": util.BasicAuth("phil", "phil"),
  789. })
  790. require.Equal(t, 200, response.Code)
  791. account, err = util.UnmarshalJSON[apiAccountResponse](io.NopCloser(response.Body))
  792. require.Nil(t, err)
  793. require.Equal(t, int64(0), account.Stats.Messages)
  794. // Since this is a user without a tier, the anonymous user should have the same stats
  795. response = request(t, s, "GET", "/v1/account", "", nil)
  796. require.Equal(t, 200, response.Code)
  797. account, err = util.UnmarshalJSON[apiAccountResponse](io.NopCloser(response.Body))
  798. require.Nil(t, err)
  799. require.Equal(t, int64(0), account.Stats.Messages)
  800. // User stats show 0 messages (for user with tier)
  801. response = request(t, s, "GET", "/v1/account", "", map[string]string{
  802. "Authorization": util.BasicAuth("tieruser", "tieruser"),
  803. })
  804. require.Equal(t, 200, response.Code)
  805. account, err = util.UnmarshalJSON[apiAccountResponse](io.NopCloser(response.Body))
  806. require.Nil(t, err)
  807. require.Equal(t, int64(0), account.Stats.Messages)
  808. }
  809. func TestServer_StatsResetter_MessageLimiter_EmailsLimiter(t *testing.T) {
  810. // This tests that the messageLimiter (the only fixed limiter) and the emailsLimiter (token bucket)
  811. // is reset by the stats resetter
  812. c := newTestConfigWithAuthFile(t)
  813. s := newTestServer(t, c)
  814. s.smtpSender = &testMailer{}
  815. // Publish some messages, and check stats
  816. for i := 0; i < 3; i++ {
  817. response := request(t, s, "PUT", "/mytopic", "test", nil)
  818. require.Equal(t, 200, response.Code)
  819. }
  820. response := request(t, s, "PUT", "/mytopic", "test", map[string]string{
  821. "Email": "test@email.com",
  822. })
  823. require.Equal(t, 200, response.Code)
  824. rr := request(t, s, "GET", "/v1/account", "", nil)
  825. require.Equal(t, 200, rr.Code)
  826. account, err := util.UnmarshalJSON[apiAccountResponse](io.NopCloser(rr.Body))
  827. require.Nil(t, err)
  828. require.Equal(t, int64(4), account.Stats.Messages)
  829. require.Equal(t, int64(1), account.Stats.Emails)
  830. v := s.visitor(netip.MustParseAddr("9.9.9.9"), nil)
  831. require.Equal(t, int64(4), v.Stats().Messages)
  832. require.Equal(t, int64(4), v.messagesLimiter.Value())
  833. require.Equal(t, int64(1), v.Stats().Emails)
  834. require.Equal(t, int64(1), v.emailsLimiter.Value())
  835. // Reset stats and check again
  836. s.resetStats()
  837. rr = request(t, s, "GET", "/v1/account", "", nil)
  838. require.Equal(t, 200, rr.Code)
  839. account, err = util.UnmarshalJSON[apiAccountResponse](io.NopCloser(rr.Body))
  840. require.Nil(t, err)
  841. require.Equal(t, int64(0), account.Stats.Messages)
  842. require.Equal(t, int64(0), account.Stats.Emails)
  843. v = s.visitor(netip.MustParseAddr("9.9.9.9"), nil)
  844. require.Equal(t, int64(0), v.Stats().Messages)
  845. require.Equal(t, int64(0), v.messagesLimiter.Value())
  846. require.Equal(t, int64(0), v.Stats().Emails)
  847. require.Equal(t, int64(0), v.emailsLimiter.Value())
  848. }
  849. func TestServer_DailyMessageQuotaFromDatabase(t *testing.T) {
  850. t.Parallel()
  851. // This tests that the daily message quota is prefilled originally from the database,
  852. // if the visitor is unknown
  853. c := newTestConfigWithAuthFile(t)
  854. c.AuthStatsQueueWriterInterval = 100 * time.Millisecond
  855. s := newTestServer(t, c)
  856. // Create user, and update it with some message and email stats
  857. require.Nil(t, s.userManager.AddTier(&user.Tier{
  858. Code: "test",
  859. }))
  860. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser))
  861. require.Nil(t, s.userManager.ChangeTier("phil", "test"))
  862. u, err := s.userManager.User("phil")
  863. require.Nil(t, err)
  864. s.userManager.EnqueueUserStats(u.ID, &user.Stats{
  865. Messages: 123456,
  866. Emails: 999,
  867. })
  868. time.Sleep(400 * time.Millisecond)
  869. // Get account and verify stats are read from the DB, and that the visitor also has these stats
  870. rr := request(t, s, "GET", "/v1/account", "", map[string]string{
  871. "Authorization": util.BasicAuth("phil", "phil"),
  872. })
  873. require.Equal(t, 200, rr.Code)
  874. account, err := util.UnmarshalJSON[apiAccountResponse](io.NopCloser(rr.Body))
  875. require.Nil(t, err)
  876. require.Equal(t, int64(123456), account.Stats.Messages)
  877. require.Equal(t, int64(999), account.Stats.Emails)
  878. v := s.visitor(netip.MustParseAddr("9.9.9.9"), u)
  879. require.Equal(t, int64(123456), v.Stats().Messages)
  880. require.Equal(t, int64(123456), v.messagesLimiter.Value())
  881. require.Equal(t, int64(999), v.Stats().Emails)
  882. require.Equal(t, int64(999), v.emailsLimiter.Value())
  883. }
  884. type testMailer struct {
  885. count int
  886. mu sync.Mutex
  887. }
  888. func (t *testMailer) Send(v *visitor, m *message, to string) error {
  889. t.mu.Lock()
  890. defer t.mu.Unlock()
  891. t.count++
  892. return nil
  893. }
  894. func (t *testMailer) Counts() (total int64, success int64, failure int64) {
  895. return 0, 0, 0
  896. }
  897. func (t *testMailer) Count() int {
  898. t.mu.Lock()
  899. defer t.mu.Unlock()
  900. return t.count
  901. }
  902. func TestServer_PublishTooRequests_Defaults(t *testing.T) {
  903. s := newTestServer(t, newTestConfig(t))
  904. for i := 0; i < 60; i++ {
  905. response := request(t, s, "PUT", "/mytopic", fmt.Sprintf("message %d", i), nil)
  906. require.Equal(t, 200, response.Code)
  907. }
  908. response := request(t, s, "PUT", "/mytopic", "message", nil)
  909. require.Equal(t, 429, response.Code)
  910. }
  911. func TestServer_PublishTooRequests_Defaults_ExemptHosts(t *testing.T) {
  912. c := newTestConfig(t)
  913. c.VisitorRequestLimitBurst = 3
  914. c.VisitorRequestExemptIPAddrs = []netip.Prefix{netip.MustParsePrefix("9.9.9.9/32")} // see request()
  915. s := newTestServer(t, c)
  916. for i := 0; i < 5; i++ { // > 3
  917. response := request(t, s, "PUT", "/mytopic", fmt.Sprintf("message %d", i), nil)
  918. require.Equal(t, 200, response.Code)
  919. }
  920. }
  921. func TestServer_PublishTooRequests_Defaults_ExemptHosts_MessageDailyLimit(t *testing.T) {
  922. c := newTestConfig(t)
  923. c.VisitorRequestLimitBurst = 10
  924. c.VisitorMessageDailyLimit = 4
  925. c.VisitorRequestExemptIPAddrs = []netip.Prefix{netip.MustParsePrefix("9.9.9.9/32")} // see request()
  926. s := newTestServer(t, c)
  927. for i := 0; i < 8; i++ { // 4
  928. response := request(t, s, "PUT", "/mytopic", "message", nil)
  929. require.Equal(t, 200, response.Code)
  930. }
  931. }
  932. func TestServer_PublishTooRequests_ShortReplenish(t *testing.T) {
  933. t.Parallel()
  934. c := newTestConfig(t)
  935. c.VisitorRequestLimitBurst = 60
  936. c.VisitorRequestLimitReplenish = time.Second
  937. s := newTestServer(t, c)
  938. for i := 0; i < 60; i++ {
  939. response := request(t, s, "PUT", "/mytopic", fmt.Sprintf("message %d", i), nil)
  940. require.Equal(t, 200, response.Code)
  941. }
  942. response := request(t, s, "PUT", "/mytopic", "message", nil)
  943. require.Equal(t, 429, response.Code)
  944. time.Sleep(1020 * time.Millisecond)
  945. response = request(t, s, "PUT", "/mytopic", "message", nil)
  946. require.Equal(t, 200, response.Code)
  947. }
  948. func TestServer_PublishTooManyEmails_Defaults(t *testing.T) {
  949. s := newTestServer(t, newTestConfig(t))
  950. s.smtpSender = &testMailer{}
  951. for i := 0; i < 16; i++ {
  952. response := request(t, s, "PUT", "/mytopic", fmt.Sprintf("message %d", i), map[string]string{
  953. "E-Mail": "test@example.com",
  954. })
  955. require.Equal(t, 200, response.Code)
  956. }
  957. response := request(t, s, "PUT", "/mytopic", "one too many", map[string]string{
  958. "E-Mail": "test@example.com",
  959. })
  960. require.Equal(t, 429, response.Code)
  961. }
  962. func TestServer_PublishTooManyEmails_Replenish(t *testing.T) {
  963. t.Parallel()
  964. c := newTestConfig(t)
  965. c.VisitorEmailLimitReplenish = 500 * time.Millisecond
  966. s := newTestServer(t, c)
  967. s.smtpSender = &testMailer{}
  968. for i := 0; i < 16; i++ {
  969. response := request(t, s, "PUT", "/mytopic", fmt.Sprintf("message %d", i), map[string]string{
  970. "E-Mail": "test@example.com",
  971. })
  972. require.Equal(t, 200, response.Code)
  973. }
  974. response := request(t, s, "PUT", "/mytopic", "one too many", map[string]string{
  975. "E-Mail": "test@example.com",
  976. })
  977. require.Equal(t, 429, response.Code)
  978. time.Sleep(510 * time.Millisecond)
  979. response = request(t, s, "PUT", "/mytopic", "this should be okay again too many", map[string]string{
  980. "E-Mail": "test@example.com",
  981. })
  982. require.Equal(t, 200, response.Code)
  983. response = request(t, s, "PUT", "/mytopic", "and bad again", map[string]string{
  984. "E-Mail": "test@example.com",
  985. })
  986. require.Equal(t, 429, response.Code)
  987. }
  988. func TestServer_PublishDelayedEmail_Fail(t *testing.T) {
  989. s := newTestServer(t, newTestConfig(t))
  990. s.smtpSender = &testMailer{}
  991. response := request(t, s, "PUT", "/mytopic", "fail", map[string]string{
  992. "E-Mail": "test@example.com",
  993. "Delay": "20 min",
  994. })
  995. require.Equal(t, 40003, toHTTPError(t, response.Body.String()).Code)
  996. }
  997. func TestServer_PublishDelayedCall_Fail(t *testing.T) {
  998. c := newTestConfigWithAuthFile(t)
  999. c.TwilioAccount = "AC1234567890"
  1000. c.TwilioAuthToken = "AAEAA1234567890"
  1001. c.TwilioPhoneNumber = "+1234567890"
  1002. s := newTestServer(t, c)
  1003. response := request(t, s, "PUT", "/mytopic", "fail", map[string]string{
  1004. "Call": "yes",
  1005. "Delay": "20 min",
  1006. })
  1007. require.Equal(t, 40037, toHTTPError(t, response.Body.String()).Code)
  1008. }
  1009. func TestServer_PublishEmailNoMailer_Fail(t *testing.T) {
  1010. s := newTestServer(t, newTestConfig(t))
  1011. response := request(t, s, "PUT", "/mytopic", "fail", map[string]string{
  1012. "E-Mail": "test@example.com",
  1013. })
  1014. require.Equal(t, 400, response.Code)
  1015. }
  1016. func TestServer_PublishAndExpungeTopicAfter16Hours(t *testing.T) {
  1017. t.Parallel()
  1018. s := newTestServer(t, newTestConfig(t))
  1019. subFn := func(v *visitor, msg *message) error {
  1020. return nil
  1021. }
  1022. // Publish and check last access
  1023. response := request(t, s, "POST", "/mytopic", "test", map[string]string{
  1024. "Cache": "no",
  1025. })
  1026. require.Equal(t, 200, response.Code)
  1027. waitFor(t, func() bool {
  1028. // .lastAccess set in t.Publish() -> t.Keepalive() in Goroutine
  1029. s.topics["mytopic"].mu.RLock()
  1030. defer s.topics["mytopic"].mu.RUnlock()
  1031. return s.topics["mytopic"].lastAccess.Unix() >= time.Now().Unix()-2 &&
  1032. s.topics["mytopic"].lastAccess.Unix() <= time.Now().Unix()+2
  1033. })
  1034. // Topic won't get pruned
  1035. s.execManager()
  1036. require.NotNil(t, s.topics["mytopic"])
  1037. // Fudge with last access, but subscribe, and see that it won't get pruned (because of subscriber)
  1038. subID := s.topics["mytopic"].Subscribe(subFn, "", func() {})
  1039. s.topics["mytopic"].mu.Lock()
  1040. s.topics["mytopic"].lastAccess = time.Now().Add(-17 * time.Hour)
  1041. s.topics["mytopic"].mu.Unlock()
  1042. s.execManager()
  1043. require.NotNil(t, s.topics["mytopic"])
  1044. // It'll finally get pruned now that there are no subscribers and last access is 17 hours ago
  1045. s.topics["mytopic"].Unsubscribe(subID)
  1046. s.execManager()
  1047. require.Nil(t, s.topics["mytopic"])
  1048. }
  1049. func TestServer_TopicKeepaliveOnPoll(t *testing.T) {
  1050. t.Parallel()
  1051. s := newTestServer(t, newTestConfig(t))
  1052. // Create topic by polling once
  1053. response := request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  1054. require.Equal(t, 200, response.Code)
  1055. // Mess with last access time
  1056. s.topics["mytopic"].lastAccess = time.Now().Add(-17 * time.Hour)
  1057. // Poll again and check keepalive time
  1058. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  1059. require.Equal(t, 200, response.Code)
  1060. require.True(t, s.topics["mytopic"].lastAccess.Unix() >= time.Now().Unix()-2)
  1061. require.True(t, s.topics["mytopic"].lastAccess.Unix() <= time.Now().Unix()+2)
  1062. }
  1063. func TestServer_UnifiedPushDiscovery(t *testing.T) {
  1064. s := newTestServer(t, newTestConfig(t))
  1065. response := request(t, s, "GET", "/mytopic?up=1", "", nil)
  1066. require.Equal(t, 200, response.Code)
  1067. require.Equal(t, `{"unifiedpush":{"version":1}}`+"\n", response.Body.String())
  1068. }
  1069. func TestServer_PublishUnifiedPushBinary_AndPoll(t *testing.T) {
  1070. b := make([]byte, 12) // Max length
  1071. _, err := rand.Read(b)
  1072. require.Nil(t, err)
  1073. s := newTestServer(t, newTestConfig(t))
  1074. // Register a UnifiedPush subscriber
  1075. response := request(t, s, "GET", "/up123456789012/json?poll=1", "", map[string]string{
  1076. "Rate-Topics": "up123456789012",
  1077. })
  1078. require.Equal(t, 200, response.Code)
  1079. // Publish message to topic
  1080. response = request(t, s, "PUT", "/up123456789012?up=1", string(b), nil)
  1081. require.Equal(t, 200, response.Code)
  1082. m := toMessage(t, response.Body.String())
  1083. require.Equal(t, "base64", m.Encoding)
  1084. b2, err := base64.StdEncoding.DecodeString(m.Message)
  1085. require.Nil(t, err)
  1086. require.Equal(t, b, b2)
  1087. // Retrieve and check published message
  1088. response = request(t, s, "GET", "/up123456789012/json?poll=1", string(b), nil)
  1089. require.Equal(t, 200, response.Code)
  1090. m = toMessage(t, response.Body.String())
  1091. require.Equal(t, "base64", m.Encoding)
  1092. b2, err = base64.StdEncoding.DecodeString(m.Message)
  1093. require.Nil(t, err)
  1094. require.Equal(t, b, b2)
  1095. }
  1096. func TestServer_PublishUnifiedPushBinary_Truncated(t *testing.T) {
  1097. b := make([]byte, 5000) // Longer than max length
  1098. _, err := rand.Read(b)
  1099. require.Nil(t, err)
  1100. s := newTestServer(t, newTestConfig(t))
  1101. // Register a UnifiedPush subscriber
  1102. response := request(t, s, "GET", "/mytopic/json?poll=1", "", map[string]string{
  1103. "Rate-Topics": "mytopic",
  1104. })
  1105. require.Equal(t, 200, response.Code)
  1106. // Publish message to topic
  1107. response = request(t, s, "PUT", "/mytopic?up=1", string(b), nil)
  1108. require.Equal(t, 200, response.Code)
  1109. m := toMessage(t, response.Body.String())
  1110. require.Equal(t, "base64", m.Encoding)
  1111. b2, err := base64.StdEncoding.DecodeString(m.Message)
  1112. require.Nil(t, err)
  1113. require.Equal(t, 4096, len(b2))
  1114. require.Equal(t, b[:4096], b2)
  1115. }
  1116. func TestServer_PublishUnifiedPushText(t *testing.T) {
  1117. s := newTestServer(t, newTestConfig(t))
  1118. // Register a UnifiedPush subscriber
  1119. response := request(t, s, "GET", "/mytopic/json?poll=1", "", map[string]string{
  1120. "Rate-Topics": "mytopic",
  1121. })
  1122. require.Equal(t, 200, response.Code)
  1123. // Publish UnifiedPush text message
  1124. response = request(t, s, "PUT", "/mytopic?up=1", "this is a unifiedpush text message", nil)
  1125. require.Equal(t, 200, response.Code)
  1126. m := toMessage(t, response.Body.String())
  1127. require.Equal(t, "", m.Encoding)
  1128. require.Equal(t, "this is a unifiedpush text message", m.Message)
  1129. }
  1130. func TestServer_MatrixGateway_Discovery_Success(t *testing.T) {
  1131. s := newTestServer(t, newTestConfig(t))
  1132. response := request(t, s, "GET", "/_matrix/push/v1/notify", "", nil)
  1133. require.Equal(t, 200, response.Code)
  1134. require.Equal(t, `{"unifiedpush":{"gateway":"matrix"}}`+"\n", response.Body.String())
  1135. }
  1136. func TestServer_MatrixGateway_Discovery_Failure_Unconfigured(t *testing.T) {
  1137. c := newTestConfig(t)
  1138. c.BaseURL = ""
  1139. s := newTestServer(t, c)
  1140. response := request(t, s, "GET", "/_matrix/push/v1/notify", "", nil)
  1141. require.Equal(t, 500, response.Code)
  1142. err := toHTTPError(t, response.Body.String())
  1143. require.Equal(t, 50003, err.Code)
  1144. }
  1145. func TestServer_MatrixGateway_Push_Success(t *testing.T) {
  1146. s := newTestServer(t, newTestConfig(t))
  1147. response := request(t, s, "GET", "/mytopic/json?poll=1", "", map[string]string{
  1148. "Rate-Topics": "mytopic", // Register first!
  1149. })
  1150. require.Equal(t, 200, response.Code)
  1151. notification := `{"notification":{"devices":[{"pushkey":"http://127.0.0.1:12345/mytopic?up=1"}]}}`
  1152. response = request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1153. require.Equal(t, 200, response.Code)
  1154. require.Equal(t, `{"rejected":[]}`+"\n", response.Body.String())
  1155. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  1156. require.Equal(t, 200, response.Code)
  1157. m := toMessage(t, response.Body.String())
  1158. require.Equal(t, notification, m.Message)
  1159. }
  1160. func TestServer_MatrixGateway_Push_Failure_NoSubscriber(t *testing.T) {
  1161. c := newTestConfig(t)
  1162. c.VisitorSubscriberRateLimiting = true
  1163. s := newTestServer(t, c)
  1164. notification := `{"notification":{"devices":[{"pushkey":"http://127.0.0.1:12345/mytopic?up=1"}]}}`
  1165. response := request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1166. require.Equal(t, 507, response.Code)
  1167. require.Equal(t, 50701, toHTTPError(t, response.Body.String()).Code)
  1168. }
  1169. func TestServer_MatrixGateway_Push_Failure_NoSubscriber_After13Hours(t *testing.T) {
  1170. c := newTestConfig(t)
  1171. c.VisitorSubscriberRateLimiting = true
  1172. s := newTestServer(t, c)
  1173. notification := `{"notification":{"devices":[{"pushkey":"http://127.0.0.1:12345/mytopic?up=1"}]}}`
  1174. // No success if no rate visitor set (this also creates the topic in memory)
  1175. response := request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1176. require.Equal(t, 507, response.Code)
  1177. require.Equal(t, 50701, toHTTPError(t, response.Body.String()).Code)
  1178. require.Nil(t, s.topics["mytopic"].rateVisitor)
  1179. // Fake: This topic has been around for 13 hours without a rate visitor
  1180. s.topics["mytopic"].lastAccess = time.Now().Add(-13 * time.Hour)
  1181. // Same request should now return HTTP 200 with a rejected pushkey
  1182. response = request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1183. require.Equal(t, 200, response.Code)
  1184. require.Equal(t, `{"rejected":["http://127.0.0.1:12345/mytopic?up=1"]}`, strings.TrimSpace(response.Body.String()))
  1185. // Slightly unrelated: Test that topic is pruned after 16 hours
  1186. s.topics["mytopic"].lastAccess = time.Now().Add(-17 * time.Hour)
  1187. s.execManager()
  1188. require.Nil(t, s.topics["mytopic"])
  1189. }
  1190. func TestServer_MatrixGateway_Push_Failure_InvalidPushkey(t *testing.T) {
  1191. s := newTestServer(t, newTestConfig(t))
  1192. notification := `{"notification":{"devices":[{"pushkey":"http://wrong-base-url.com/mytopic?up=1"}]}}`
  1193. response := request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1194. require.Equal(t, 200, response.Code)
  1195. require.Equal(t, `{"rejected":["http://wrong-base-url.com/mytopic?up=1"]}`+"\n", response.Body.String())
  1196. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  1197. require.Equal(t, 200, response.Code)
  1198. require.Equal(t, "", response.Body.String()) // Empty!
  1199. }
  1200. func TestServer_MatrixGateway_Push_Failure_EverythingIsWrong(t *testing.T) {
  1201. s := newTestServer(t, newTestConfig(t))
  1202. notification := `{"message":"this is not really a Matrix message"}`
  1203. response := request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1204. require.Equal(t, 400, response.Code)
  1205. require.Equal(t, 40019, toHTTPError(t, response.Body.String()).Code)
  1206. notification = `this isn't even JSON'`
  1207. response = request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1208. require.Equal(t, 400, response.Code)
  1209. require.Equal(t, 40019, toHTTPError(t, response.Body.String()).Code)
  1210. }
  1211. func TestServer_MatrixGateway_Push_Failure_Unconfigured(t *testing.T) {
  1212. c := newTestConfig(t)
  1213. c.BaseURL = ""
  1214. s := newTestServer(t, c)
  1215. notification := `{"notification":{"devices":[{"pushkey":"http://127.0.0.1:12345/mytopic?up=1"}]}}`
  1216. response := request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1217. require.Equal(t, 500, response.Code)
  1218. require.Equal(t, 50003, toHTTPError(t, response.Body.String()).Code)
  1219. }
  1220. func TestServer_PublishActions_AndPoll(t *testing.T) {
  1221. s := newTestServer(t, newTestConfig(t))
  1222. response := request(t, s, "PUT", "/mytopic", "my message", map[string]string{
  1223. "Actions": "view, Open portal, https://home.nest.com/; http, Turn down, https://api.nest.com/device/XZ1D2, body=target_temp_f=65",
  1224. })
  1225. require.Equal(t, 200, response.Code)
  1226. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  1227. require.Equal(t, 200, response.Code)
  1228. m := toMessage(t, response.Body.String())
  1229. require.Equal(t, 2, len(m.Actions))
  1230. require.Equal(t, "view", m.Actions[0].Action)
  1231. require.Equal(t, "Open portal", m.Actions[0].Label)
  1232. require.Equal(t, "https://home.nest.com/", m.Actions[0].URL)
  1233. require.Equal(t, "http", m.Actions[1].Action)
  1234. require.Equal(t, "Turn down", m.Actions[1].Label)
  1235. require.Equal(t, "https://api.nest.com/device/XZ1D2", m.Actions[1].URL)
  1236. require.Equal(t, "target_temp_f=65", m.Actions[1].Body)
  1237. }
  1238. func TestServer_PublishAsJSON(t *testing.T) {
  1239. s := newTestServer(t, newTestConfig(t))
  1240. body := `{"topic":"mytopic","message":"A message","title":"a title\nwith lines","tags":["tag1","tag 2"],` +
  1241. `"not-a-thing":"ok", "attach":"http://google.com","filename":"google.pdf", "click":"http://ntfy.sh","priority":4,` +
  1242. `"icon":"https://ntfy.sh/static/img/ntfy.png", "delay":"30min"}`
  1243. response := request(t, s, "PUT", "/", body, nil)
  1244. require.Equal(t, 200, response.Code)
  1245. m := toMessage(t, response.Body.String())
  1246. require.Equal(t, "mytopic", m.Topic)
  1247. require.Equal(t, "A message", m.Message)
  1248. require.Equal(t, "a title\nwith lines", m.Title)
  1249. require.Equal(t, []string{"tag1", "tag 2"}, m.Tags)
  1250. require.Equal(t, "http://google.com", m.Attachment.URL)
  1251. require.Equal(t, "google.pdf", m.Attachment.Name)
  1252. require.Equal(t, "http://ntfy.sh", m.Click)
  1253. require.Equal(t, "https://ntfy.sh/static/img/ntfy.png", m.Icon)
  1254. require.Equal(t, 4, m.Priority)
  1255. require.True(t, m.Time > time.Now().Unix()+29*60)
  1256. require.True(t, m.Time < time.Now().Unix()+31*60)
  1257. }
  1258. func TestServer_PublishAsJSON_RateLimit_MessageDailyLimit(t *testing.T) {
  1259. // Publishing as JSON follows a different path. This ensures that rate
  1260. // limiting works for this endpoint as well
  1261. c := newTestConfig(t)
  1262. c.VisitorMessageDailyLimit = 3
  1263. s := newTestServer(t, c)
  1264. for i := 0; i < 3; i++ {
  1265. response := request(t, s, "PUT", "/", `{"topic":"mytopic","message":"A message"}`, nil)
  1266. require.Equal(t, 200, response.Code)
  1267. }
  1268. response := request(t, s, "PUT", "/", `{"topic":"mytopic","message":"A message"}`, nil)
  1269. require.Equal(t, 429, response.Code)
  1270. require.Equal(t, 42908, toHTTPError(t, response.Body.String()).Code)
  1271. }
  1272. func TestServer_PublishAsJSON_WithEmail(t *testing.T) {
  1273. t.Parallel()
  1274. mailer := &testMailer{}
  1275. s := newTestServer(t, newTestConfig(t))
  1276. s.smtpSender = mailer
  1277. body := `{"topic":"mytopic","message":"A message","email":"phil@example.com"}`
  1278. response := request(t, s, "PUT", "/", body, nil)
  1279. require.Equal(t, 200, response.Code)
  1280. time.Sleep(100 * time.Millisecond) // E-Mail publishing happens in a Go routine
  1281. m := toMessage(t, response.Body.String())
  1282. require.Equal(t, "mytopic", m.Topic)
  1283. require.Equal(t, "A message", m.Message)
  1284. require.Equal(t, 1, mailer.Count())
  1285. }
  1286. func TestServer_PublishAsJSON_WithActions(t *testing.T) {
  1287. s := newTestServer(t, newTestConfig(t))
  1288. body := `{
  1289. "topic":"mytopic",
  1290. "message":"A message",
  1291. "actions": [
  1292. {
  1293. "action": "view",
  1294. "label": "Open portal",
  1295. "url": "https://home.nest.com/"
  1296. },
  1297. {
  1298. "action": "http",
  1299. "label": "Turn down",
  1300. "url": "https://api.nest.com/device/XZ1D2",
  1301. "body": "target_temp_f=65"
  1302. }
  1303. ]
  1304. }`
  1305. response := request(t, s, "POST", "/", body, nil)
  1306. require.Equal(t, 200, response.Code)
  1307. m := toMessage(t, response.Body.String())
  1308. require.Equal(t, "mytopic", m.Topic)
  1309. require.Equal(t, "A message", m.Message)
  1310. require.Equal(t, 2, len(m.Actions))
  1311. require.Equal(t, "view", m.Actions[0].Action)
  1312. require.Equal(t, "Open portal", m.Actions[0].Label)
  1313. require.Equal(t, "https://home.nest.com/", m.Actions[0].URL)
  1314. require.Equal(t, "http", m.Actions[1].Action)
  1315. require.Equal(t, "Turn down", m.Actions[1].Label)
  1316. require.Equal(t, "https://api.nest.com/device/XZ1D2", m.Actions[1].URL)
  1317. require.Equal(t, "target_temp_f=65", m.Actions[1].Body)
  1318. }
  1319. func TestServer_PublishAsJSON_Invalid(t *testing.T) {
  1320. s := newTestServer(t, newTestConfig(t))
  1321. body := `{"topic":"mytopic",INVALID`
  1322. response := request(t, s, "PUT", "/", body, nil)
  1323. require.Equal(t, 400, response.Code)
  1324. }
  1325. func TestServer_PublishWithTierBasedMessageLimitAndExpiry(t *testing.T) {
  1326. c := newTestConfigWithAuthFile(t)
  1327. s := newTestServer(t, c)
  1328. // Create tier with certain limits
  1329. require.Nil(t, s.userManager.AddTier(&user.Tier{
  1330. Code: "test",
  1331. MessageLimit: 5,
  1332. MessageExpiryDuration: -5 * time.Second, // Second, what a hack!
  1333. }))
  1334. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser))
  1335. require.Nil(t, s.userManager.ChangeTier("phil", "test"))
  1336. // Publish to reach message limit
  1337. for i := 0; i < 5; i++ {
  1338. response := request(t, s, "PUT", "/mytopic", fmt.Sprintf("this is message %d", i+1), map[string]string{
  1339. "Authorization": util.BasicAuth("phil", "phil"),
  1340. })
  1341. require.Equal(t, 200, response.Code)
  1342. msg := toMessage(t, response.Body.String())
  1343. require.True(t, msg.Expires < time.Now().Unix()+5)
  1344. }
  1345. response := request(t, s, "PUT", "/mytopic", "this is too much", map[string]string{
  1346. "Authorization": util.BasicAuth("phil", "phil"),
  1347. })
  1348. require.Equal(t, 429, response.Code)
  1349. // Run pruning and see if they are gone
  1350. s.execManager()
  1351. response = request(t, s, "GET", "/mytopic/json?poll=1", "", map[string]string{
  1352. "Authorization": util.BasicAuth("phil", "phil"),
  1353. })
  1354. require.Equal(t, 200, response.Code)
  1355. require.Empty(t, response.Body)
  1356. }
  1357. func TestServer_PublishAttachment(t *testing.T) {
  1358. content := "text file!" + util.RandomString(4990) // > 4096
  1359. s := newTestServer(t, newTestConfig(t))
  1360. response := request(t, s, "PUT", "/mytopic", content, nil)
  1361. msg := toMessage(t, response.Body.String())
  1362. require.Equal(t, "attachment.txt", msg.Attachment.Name)
  1363. require.Equal(t, "text/plain; charset=utf-8", msg.Attachment.Type)
  1364. require.Equal(t, int64(5000), msg.Attachment.Size)
  1365. require.GreaterOrEqual(t, msg.Attachment.Expires, time.Now().Add(179*time.Minute).Unix()) // Almost 3 hours
  1366. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1367. require.Equal(t, netip.Addr{}, msg.Sender) // Should never be returned
  1368. require.FileExists(t, filepath.Join(s.config.AttachmentCacheDir, msg.ID))
  1369. // GET
  1370. path := strings.TrimPrefix(msg.Attachment.URL, "http://127.0.0.1:12345")
  1371. response = request(t, s, "GET", path, "", nil)
  1372. require.Equal(t, 200, response.Code)
  1373. require.Equal(t, "5000", response.Header().Get("Content-Length"))
  1374. require.Equal(t, content, response.Body.String())
  1375. // HEAD
  1376. response = request(t, s, "HEAD", path, "", nil)
  1377. require.Equal(t, 200, response.Code)
  1378. require.Equal(t, "5000", response.Header().Get("Content-Length"))
  1379. require.Equal(t, "", response.Body.String())
  1380. // Slightly unrelated cross-test: make sure we add an owner for internal attachments
  1381. size, err := s.messageCache.AttachmentBytesUsedBySender("9.9.9.9") // See request()
  1382. require.Nil(t, err)
  1383. require.Equal(t, int64(5000), size)
  1384. }
  1385. func TestServer_PublishAttachmentShortWithFilename(t *testing.T) {
  1386. c := newTestConfig(t)
  1387. c.BehindProxy = true
  1388. s := newTestServer(t, c)
  1389. content := "this is an ATTACHMENT"
  1390. response := request(t, s, "PUT", "/mytopic?f=myfile.txt", content, map[string]string{
  1391. "X-Forwarded-For": "1.2.3.4",
  1392. })
  1393. msg := toMessage(t, response.Body.String())
  1394. require.Equal(t, "myfile.txt", msg.Attachment.Name)
  1395. require.Equal(t, "text/plain; charset=utf-8", msg.Attachment.Type)
  1396. require.Equal(t, int64(21), msg.Attachment.Size)
  1397. require.GreaterOrEqual(t, msg.Attachment.Expires, time.Now().Add(3*time.Hour).Unix())
  1398. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1399. require.Equal(t, netip.Addr{}, msg.Sender) // Should never be returned
  1400. require.FileExists(t, filepath.Join(s.config.AttachmentCacheDir, msg.ID))
  1401. path := strings.TrimPrefix(msg.Attachment.URL, "http://127.0.0.1:12345")
  1402. response = request(t, s, "GET", path, "", nil)
  1403. require.Equal(t, 200, response.Code)
  1404. require.Equal(t, "21", response.Header().Get("Content-Length"))
  1405. require.Equal(t, content, response.Body.String())
  1406. // Slightly unrelated cross-test: make sure we add an owner for internal attachments
  1407. size, err := s.messageCache.AttachmentBytesUsedBySender("1.2.3.4")
  1408. require.Nil(t, err)
  1409. require.Equal(t, int64(21), size)
  1410. }
  1411. func TestServer_PublishAttachmentExternalWithoutFilename(t *testing.T) {
  1412. s := newTestServer(t, newTestConfig(t))
  1413. response := request(t, s, "PUT", "/mytopic", "", map[string]string{
  1414. "Attach": "https://upload.wikimedia.org/wikipedia/commons/f/fd/Pink_flower.jpg",
  1415. })
  1416. msg := toMessage(t, response.Body.String())
  1417. require.Equal(t, "You received a file: Pink_flower.jpg", msg.Message)
  1418. require.Equal(t, "Pink_flower.jpg", msg.Attachment.Name)
  1419. require.Equal(t, "https://upload.wikimedia.org/wikipedia/commons/f/fd/Pink_flower.jpg", msg.Attachment.URL)
  1420. require.Equal(t, "", msg.Attachment.Type)
  1421. require.Equal(t, int64(0), msg.Attachment.Size)
  1422. require.Equal(t, int64(0), msg.Attachment.Expires)
  1423. require.Equal(t, netip.Addr{}, msg.Sender)
  1424. // Slightly unrelated cross-test: make sure we don't add an owner for external attachments
  1425. size, err := s.messageCache.AttachmentBytesUsedBySender("127.0.0.1")
  1426. require.Nil(t, err)
  1427. require.Equal(t, int64(0), size)
  1428. }
  1429. func TestServer_PublishAttachmentExternalWithFilename(t *testing.T) {
  1430. s := newTestServer(t, newTestConfig(t))
  1431. response := request(t, s, "PUT", "/mytopic", "This is a custom message", map[string]string{
  1432. "X-Attach": "https://upload.wikimedia.org/wikipedia/commons/f/fd/Pink_flower.jpg",
  1433. "File": "some file.jpg",
  1434. })
  1435. msg := toMessage(t, response.Body.String())
  1436. require.Equal(t, "This is a custom message", msg.Message)
  1437. require.Equal(t, "some file.jpg", msg.Attachment.Name)
  1438. require.Equal(t, "https://upload.wikimedia.org/wikipedia/commons/f/fd/Pink_flower.jpg", msg.Attachment.URL)
  1439. require.Equal(t, "", msg.Attachment.Type)
  1440. require.Equal(t, int64(0), msg.Attachment.Size)
  1441. require.Equal(t, int64(0), msg.Attachment.Expires)
  1442. require.Equal(t, netip.Addr{}, msg.Sender)
  1443. }
  1444. func TestServer_PublishAttachmentBadURL(t *testing.T) {
  1445. s := newTestServer(t, newTestConfig(t))
  1446. response := request(t, s, "PUT", "/mytopic?a=not+a+URL", "", nil)
  1447. err := toHTTPError(t, response.Body.String())
  1448. require.Equal(t, 400, response.Code)
  1449. require.Equal(t, 400, err.HTTPCode)
  1450. require.Equal(t, 40013, err.Code)
  1451. }
  1452. func TestServer_PublishAttachmentTooLargeContentLength(t *testing.T) {
  1453. content := util.RandomString(5000) // > 4096
  1454. s := newTestServer(t, newTestConfig(t))
  1455. response := request(t, s, "PUT", "/mytopic", content, map[string]string{
  1456. "Content-Length": "20000000",
  1457. })
  1458. err := toHTTPError(t, response.Body.String())
  1459. require.Equal(t, 413, response.Code)
  1460. require.Equal(t, 413, err.HTTPCode)
  1461. require.Equal(t, 41301, err.Code)
  1462. }
  1463. func TestServer_PublishAttachmentTooLargeBodyAttachmentFileSizeLimit(t *testing.T) {
  1464. content := util.RandomString(5001) // > 5000, see below
  1465. c := newTestConfig(t)
  1466. c.AttachmentFileSizeLimit = 5000
  1467. s := newTestServer(t, c)
  1468. response := request(t, s, "PUT", "/mytopic", content, nil)
  1469. err := toHTTPError(t, response.Body.String())
  1470. require.Equal(t, 413, response.Code)
  1471. require.Equal(t, 413, err.HTTPCode)
  1472. require.Equal(t, 41301, err.Code)
  1473. }
  1474. func TestServer_PublishAttachmentExpiryBeforeDelivery(t *testing.T) {
  1475. c := newTestConfig(t)
  1476. c.AttachmentExpiryDuration = 10 * time.Minute
  1477. s := newTestServer(t, c)
  1478. response := request(t, s, "PUT", "/mytopic", util.RandomString(5000), map[string]string{
  1479. "Delay": "11 min", // > AttachmentExpiryDuration
  1480. })
  1481. err := toHTTPError(t, response.Body.String())
  1482. require.Equal(t, 400, response.Code)
  1483. require.Equal(t, 400, err.HTTPCode)
  1484. require.Equal(t, 40015, err.Code)
  1485. }
  1486. func TestServer_PublishAttachmentTooLargeBodyVisitorAttachmentTotalSizeLimit(t *testing.T) {
  1487. c := newTestConfig(t)
  1488. c.VisitorAttachmentTotalSizeLimit = 10000
  1489. s := newTestServer(t, c)
  1490. response := request(t, s, "PUT", "/mytopic", "text file!"+util.RandomString(4990), nil)
  1491. msg := toMessage(t, response.Body.String())
  1492. require.Equal(t, 200, response.Code)
  1493. require.Equal(t, "You received a file: attachment.txt", msg.Message)
  1494. require.Equal(t, int64(5000), msg.Attachment.Size)
  1495. content := util.RandomString(5001) // 5000+5001 > , see below
  1496. response = request(t, s, "PUT", "/mytopic", content, nil)
  1497. err := toHTTPError(t, response.Body.String())
  1498. require.Equal(t, 413, response.Code)
  1499. require.Equal(t, 413, err.HTTPCode)
  1500. require.Equal(t, 41301, err.Code)
  1501. }
  1502. func TestServer_PublishAttachmentAndExpire(t *testing.T) {
  1503. t.Parallel()
  1504. content := util.RandomString(5000) // > 4096
  1505. c := newTestConfig(t)
  1506. c.AttachmentExpiryDuration = time.Millisecond // Hack
  1507. s := newTestServer(t, c)
  1508. // Publish and make sure we can retrieve it
  1509. response := request(t, s, "PUT", "/mytopic", content, nil)
  1510. msg := toMessage(t, response.Body.String())
  1511. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1512. file := filepath.Join(s.config.AttachmentCacheDir, msg.ID)
  1513. require.FileExists(t, file)
  1514. path := strings.TrimPrefix(msg.Attachment.URL, "http://127.0.0.1:12345")
  1515. response = request(t, s, "GET", path, "", nil)
  1516. require.Equal(t, 200, response.Code)
  1517. require.Equal(t, content, response.Body.String())
  1518. // Prune and makes sure it's gone
  1519. waitFor(t, func() bool {
  1520. s.execManager() // May run many times
  1521. return !util.FileExists(file)
  1522. })
  1523. response = request(t, s, "GET", path, "", nil)
  1524. require.Equal(t, 404, response.Code)
  1525. }
  1526. func TestServer_PublishAttachmentWithTierBasedExpiry(t *testing.T) {
  1527. t.Parallel()
  1528. content := util.RandomString(5000) // > 4096
  1529. c := newTestConfigWithAuthFile(t)
  1530. c.AttachmentExpiryDuration = time.Millisecond // Hack
  1531. s := newTestServer(t, c)
  1532. // Create tier with certain limits
  1533. sevenDays := time.Duration(604800) * time.Second
  1534. require.Nil(t, s.userManager.AddTier(&user.Tier{
  1535. Code: "test",
  1536. MessageLimit: 10,
  1537. MessageExpiryDuration: sevenDays,
  1538. AttachmentFileSizeLimit: 50_000,
  1539. AttachmentTotalSizeLimit: 200_000,
  1540. AttachmentExpiryDuration: sevenDays, // 7 days
  1541. AttachmentBandwidthLimit: 100000,
  1542. }))
  1543. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser))
  1544. require.Nil(t, s.userManager.ChangeTier("phil", "test"))
  1545. // Publish and make sure we can retrieve it
  1546. response := request(t, s, "PUT", "/mytopic", content, map[string]string{
  1547. "Authorization": util.BasicAuth("phil", "phil"),
  1548. })
  1549. require.Equal(t, 200, response.Code)
  1550. msg := toMessage(t, response.Body.String())
  1551. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1552. require.True(t, msg.Attachment.Expires > time.Now().Add(sevenDays-30*time.Second).Unix())
  1553. require.True(t, msg.Expires > time.Now().Add(sevenDays-30*time.Second).Unix())
  1554. file := filepath.Join(s.config.AttachmentCacheDir, msg.ID)
  1555. require.FileExists(t, file)
  1556. path := strings.TrimPrefix(msg.Attachment.URL, "http://127.0.0.1:12345")
  1557. response = request(t, s, "GET", path, "", nil)
  1558. require.Equal(t, 200, response.Code)
  1559. require.Equal(t, content, response.Body.String())
  1560. // Prune and makes sure it's still there
  1561. time.Sleep(time.Second) // Sigh ...
  1562. s.execManager()
  1563. require.FileExists(t, file)
  1564. response = request(t, s, "GET", path, "", nil)
  1565. require.Equal(t, 200, response.Code)
  1566. }
  1567. func TestServer_PublishAttachmentWithTierBasedBandwidthLimit(t *testing.T) {
  1568. content := util.RandomString(5000) // > 4096
  1569. c := newTestConfigWithAuthFile(t)
  1570. c.VisitorAttachmentDailyBandwidthLimit = 1000 // Much lower than tier bandwidth!
  1571. s := newTestServer(t, c)
  1572. // Create tier with certain limits
  1573. require.Nil(t, s.userManager.AddTier(&user.Tier{
  1574. Code: "test",
  1575. MessageLimit: 10,
  1576. MessageExpiryDuration: time.Hour,
  1577. AttachmentFileSizeLimit: 50_000,
  1578. AttachmentTotalSizeLimit: 200_000,
  1579. AttachmentExpiryDuration: time.Hour,
  1580. AttachmentBandwidthLimit: 14000, // < 3x5000 bytes -> enough for one upload, one download
  1581. }))
  1582. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser))
  1583. require.Nil(t, s.userManager.ChangeTier("phil", "test"))
  1584. // Publish and make sure we can retrieve it
  1585. rr := request(t, s, "PUT", "/mytopic", content, map[string]string{
  1586. "Authorization": util.BasicAuth("phil", "phil"),
  1587. })
  1588. require.Equal(t, 200, rr.Code)
  1589. msg := toMessage(t, rr.Body.String())
  1590. // Retrieve it (first time succeeds)
  1591. rr = request(t, s, "GET", "/file/"+msg.ID, content, nil) // File downloads do not send auth headers!!
  1592. require.Equal(t, 200, rr.Code)
  1593. require.Equal(t, content, rr.Body.String())
  1594. // Retrieve it AGAIN (fails, due to bandwidth limit)
  1595. rr = request(t, s, "GET", "/file/"+msg.ID, content, nil)
  1596. require.Equal(t, 429, rr.Code)
  1597. }
  1598. func TestServer_PublishAttachmentWithTierBasedLimits(t *testing.T) {
  1599. smallFile := util.RandomString(20_000)
  1600. largeFile := util.RandomString(50_000)
  1601. c := newTestConfigWithAuthFile(t)
  1602. c.AttachmentFileSizeLimit = 20_000
  1603. c.VisitorAttachmentTotalSizeLimit = 40_000
  1604. s := newTestServer(t, c)
  1605. // Create tier with certain limits
  1606. require.Nil(t, s.userManager.AddTier(&user.Tier{
  1607. Code: "test",
  1608. MessageLimit: 100,
  1609. AttachmentFileSizeLimit: 50_000,
  1610. AttachmentTotalSizeLimit: 200_000,
  1611. AttachmentExpiryDuration: 30 * time.Second,
  1612. AttachmentBandwidthLimit: 1000000,
  1613. }))
  1614. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser))
  1615. require.Nil(t, s.userManager.ChangeTier("phil", "test"))
  1616. // Publish small file as anonymous
  1617. response := request(t, s, "PUT", "/mytopic", smallFile, nil)
  1618. msg := toMessage(t, response.Body.String())
  1619. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1620. require.FileExists(t, filepath.Join(s.config.AttachmentCacheDir, msg.ID))
  1621. // Publish large file as anonymous
  1622. response = request(t, s, "PUT", "/mytopic", largeFile, nil)
  1623. require.Equal(t, 413, response.Code)
  1624. require.Equal(t, 41301, toHTTPError(t, response.Body.String()).Code)
  1625. // Publish too large file as phil
  1626. response = request(t, s, "PUT", "/mytopic", largeFile+" a few more bytes", map[string]string{
  1627. "Authorization": util.BasicAuth("phil", "phil"),
  1628. })
  1629. require.Equal(t, 413, response.Code)
  1630. require.Equal(t, 41301, toHTTPError(t, response.Body.String()).Code)
  1631. // Publish large file as phil (4x)
  1632. for i := 0; i < 4; i++ {
  1633. response = request(t, s, "PUT", "/mytopic", largeFile, map[string]string{
  1634. "Authorization": util.BasicAuth("phil", "phil"),
  1635. })
  1636. require.Equal(t, 200, response.Code)
  1637. msg = toMessage(t, response.Body.String())
  1638. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1639. require.FileExists(t, filepath.Join(s.config.AttachmentCacheDir, msg.ID))
  1640. }
  1641. response = request(t, s, "PUT", "/mytopic", largeFile, map[string]string{
  1642. "Authorization": util.BasicAuth("phil", "phil"),
  1643. })
  1644. require.Equal(t, 413, response.Code)
  1645. require.Equal(t, 41301, toHTTPError(t, response.Body.String()).Code)
  1646. }
  1647. func TestServer_PublishAttachmentBandwidthLimit(t *testing.T) {
  1648. content := util.RandomString(5000) // > 4096
  1649. c := newTestConfig(t)
  1650. c.VisitorAttachmentDailyBandwidthLimit = 5*5000 + 123 // A little more than 1 upload and 3 downloads
  1651. s := newTestServer(t, c)
  1652. // Publish attachment
  1653. response := request(t, s, "PUT", "/mytopic", content, nil)
  1654. msg := toMessage(t, response.Body.String())
  1655. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1656. // Value it 4 times successfully
  1657. path := strings.TrimPrefix(msg.Attachment.URL, "http://127.0.0.1:12345")
  1658. for i := 1; i <= 4; i++ { // 4 successful downloads
  1659. response = request(t, s, "GET", path, "", nil)
  1660. require.Equal(t, 200, response.Code)
  1661. require.Equal(t, content, response.Body.String())
  1662. }
  1663. // And then fail with a 429
  1664. response = request(t, s, "GET", path, "", nil)
  1665. err := toHTTPError(t, response.Body.String())
  1666. require.Equal(t, 429, response.Code)
  1667. require.Equal(t, 42905, err.Code)
  1668. }
  1669. func TestServer_PublishAttachmentBandwidthLimitUploadOnly(t *testing.T) {
  1670. content := util.RandomString(5000) // > 4096
  1671. c := newTestConfig(t)
  1672. c.VisitorAttachmentDailyBandwidthLimit = 5*5000 + 500 // 5 successful uploads
  1673. s := newTestServer(t, c)
  1674. // 5 successful uploads
  1675. for i := 1; i <= 5; i++ {
  1676. response := request(t, s, "PUT", "/mytopic", content, nil)
  1677. msg := toMessage(t, response.Body.String())
  1678. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1679. }
  1680. // And a failed one
  1681. response := request(t, s, "PUT", "/mytopic", content, nil)
  1682. err := toHTTPError(t, response.Body.String())
  1683. require.Equal(t, 413, response.Code)
  1684. require.Equal(t, 41301, err.Code)
  1685. }
  1686. func TestServer_PublishAttachmentAndImmediatelyGetItWithCacheTimeout(t *testing.T) {
  1687. // This tests the awkward util.Retry in handleFile: Due to the async persisting of messages,
  1688. // the message is not immediately available when attempting to download it.
  1689. c := newTestConfig(t)
  1690. c.CacheBatchTimeout = 500 * time.Millisecond
  1691. c.CacheBatchSize = 10
  1692. s := newTestServer(t, c)
  1693. content := "this is an ATTACHMENT"
  1694. rr := request(t, s, "PUT", "/mytopic?f=myfile.txt", content, nil)
  1695. m := toMessage(t, rr.Body.String())
  1696. require.Equal(t, "myfile.txt", m.Attachment.Name)
  1697. path := strings.TrimPrefix(m.Attachment.URL, "http://127.0.0.1:12345")
  1698. rr = request(t, s, "GET", path, "", nil)
  1699. require.Equal(t, 200, rr.Code) // Not 404!
  1700. require.Equal(t, content, rr.Body.String())
  1701. }
  1702. func TestServer_PublishAttachmentAccountStats(t *testing.T) {
  1703. content := util.RandomString(4999) // > 4096
  1704. c := newTestConfig(t)
  1705. c.AttachmentFileSizeLimit = 5000
  1706. c.VisitorAttachmentTotalSizeLimit = 6000
  1707. s := newTestServer(t, c)
  1708. // Upload one attachment
  1709. response := request(t, s, "PUT", "/mytopic", content, nil)
  1710. msg := toMessage(t, response.Body.String())
  1711. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1712. // User stats
  1713. response = request(t, s, "GET", "/v1/account", "", nil)
  1714. require.Equal(t, 200, response.Code)
  1715. account, err := util.UnmarshalJSON[apiAccountResponse](io.NopCloser(response.Body))
  1716. require.Nil(t, err)
  1717. require.Equal(t, int64(5000), account.Limits.AttachmentFileSize)
  1718. require.Equal(t, int64(6000), account.Limits.AttachmentTotalSize)
  1719. require.Equal(t, int64(4999), account.Stats.AttachmentTotalSize)
  1720. require.Equal(t, int64(1001), account.Stats.AttachmentTotalSizeRemaining)
  1721. require.Equal(t, int64(1), account.Stats.Messages)
  1722. }
  1723. func TestServer_Visitor_XForwardedFor_None(t *testing.T) {
  1724. c := newTestConfig(t)
  1725. c.BehindProxy = true
  1726. s := newTestServer(t, c)
  1727. r, _ := http.NewRequest("GET", "/bla", nil)
  1728. r.RemoteAddr = "8.9.10.11"
  1729. r.Header.Set("X-Forwarded-For", " ") // Spaces, not empty!
  1730. v, err := s.maybeAuthenticate(r)
  1731. require.Nil(t, err)
  1732. require.Equal(t, "8.9.10.11", v.ip.String())
  1733. }
  1734. func TestServer_Visitor_XForwardedFor_Single(t *testing.T) {
  1735. c := newTestConfig(t)
  1736. c.BehindProxy = true
  1737. s := newTestServer(t, c)
  1738. r, _ := http.NewRequest("GET", "/bla", nil)
  1739. r.RemoteAddr = "8.9.10.11"
  1740. r.Header.Set("X-Forwarded-For", "1.1.1.1")
  1741. v, err := s.maybeAuthenticate(r)
  1742. require.Nil(t, err)
  1743. require.Equal(t, "1.1.1.1", v.ip.String())
  1744. }
  1745. func TestServer_Visitor_XForwardedFor_Multiple(t *testing.T) {
  1746. c := newTestConfig(t)
  1747. c.BehindProxy = true
  1748. s := newTestServer(t, c)
  1749. r, _ := http.NewRequest("GET", "/bla", nil)
  1750. r.RemoteAddr = "8.9.10.11"
  1751. r.Header.Set("X-Forwarded-For", "1.2.3.4 , 2.4.4.2,234.5.2.1 ")
  1752. v, err := s.maybeAuthenticate(r)
  1753. require.Nil(t, err)
  1754. require.Equal(t, "234.5.2.1", v.ip.String())
  1755. }
  1756. func TestServer_PublishWhileUpdatingStatsWithLotsOfMessages(t *testing.T) {
  1757. t.Parallel()
  1758. count := 50000
  1759. c := newTestConfig(t)
  1760. c.TotalTopicLimit = 50001
  1761. c.CacheStartupQueries = "pragma journal_mode = WAL; pragma synchronous = normal; pragma temp_store = memory;"
  1762. s := newTestServer(t, c)
  1763. // Add lots of messages
  1764. log.Info("Adding %d messages", count)
  1765. start := time.Now()
  1766. messages := make([]*message, 0)
  1767. for i := 0; i < count; i++ {
  1768. topicID := fmt.Sprintf("topic%d", i)
  1769. _, err := s.topicsFromIDs(topicID) // Add topic to internal s.topics array
  1770. require.Nil(t, err)
  1771. messages = append(messages, newDefaultMessage(topicID, "some message"))
  1772. }
  1773. require.Nil(t, s.messageCache.addMessages(messages))
  1774. log.Info("Done: Adding %d messages; took %s", count, time.Since(start).Round(time.Millisecond))
  1775. // Update stats
  1776. statsChan := make(chan bool)
  1777. go func() {
  1778. log.Info("Updating stats")
  1779. start := time.Now()
  1780. s.execManager()
  1781. log.Info("Done: Updating stats; took %s", time.Since(start).Round(time.Millisecond))
  1782. statsChan <- true
  1783. }()
  1784. time.Sleep(50 * time.Millisecond) // Make sure it starts first
  1785. // Publish message (during stats update)
  1786. log.Info("Publishing message")
  1787. start = time.Now()
  1788. response := request(t, s, "PUT", "/mytopic", "some body", nil)
  1789. m := toMessage(t, response.Body.String())
  1790. require.Equal(t, "some body", m.Message)
  1791. require.True(t, time.Since(start) < 100*time.Millisecond)
  1792. log.Info("Done: Publishing message; took %s", time.Since(start).Round(time.Millisecond))
  1793. // Wait for all goroutines
  1794. select {
  1795. case <-statsChan:
  1796. case <-time.After(10 * time.Second):
  1797. t.Fatal("Timed out waiting for Go routines")
  1798. }
  1799. log.Info("Done: Waiting for all locks")
  1800. }
  1801. func TestServer_AnonymousUser_And_NonTierUser_Are_Same_Visitor(t *testing.T) {
  1802. conf := newTestConfigWithAuthFile(t)
  1803. s := newTestServer(t, conf)
  1804. defer s.closeDatabases()
  1805. // Create user without tier
  1806. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser))
  1807. // Publish a message (anonymous user)
  1808. rr := request(t, s, "POST", "/mytopic", "hi", nil)
  1809. require.Equal(t, 200, rr.Code)
  1810. // Publish a message (non-tier user)
  1811. rr = request(t, s, "POST", "/mytopic", "hi", map[string]string{
  1812. "Authorization": util.BasicAuth("phil", "phil"),
  1813. })
  1814. require.Equal(t, 200, rr.Code)
  1815. // User stats (anonymous user)
  1816. rr = request(t, s, "GET", "/v1/account", "", nil)
  1817. account, _ := util.UnmarshalJSON[apiAccountResponse](io.NopCloser(rr.Body))
  1818. require.Equal(t, int64(2), account.Stats.Messages)
  1819. // User stats (non-tier user)
  1820. rr = request(t, s, "GET", "/v1/account", "", map[string]string{
  1821. "Authorization": util.BasicAuth("phil", "phil"),
  1822. })
  1823. account, _ = util.UnmarshalJSON[apiAccountResponse](io.NopCloser(rr.Body))
  1824. require.Equal(t, int64(2), account.Stats.Messages)
  1825. }
  1826. func TestServer_SubscriberRateLimiting_Success(t *testing.T) {
  1827. c := newTestConfigWithAuthFile(t)
  1828. c.VisitorRequestLimitBurst = 3
  1829. c.VisitorSubscriberRateLimiting = true
  1830. s := newTestServer(t, c)
  1831. // "Register" visitor 1.2.3.4 to topic "subscriber1topic" as a rate limit visitor
  1832. subscriber1Fn := func(r *http.Request) {
  1833. r.RemoteAddr = "1.2.3.4"
  1834. }
  1835. rr := request(t, s, "GET", "/subscriber1topic/json?poll=1", "", map[string]string{
  1836. "Rate-Topics": "subscriber1topic",
  1837. }, subscriber1Fn)
  1838. require.Equal(t, 200, rr.Code)
  1839. require.Equal(t, "", rr.Body.String())
  1840. require.Equal(t, "1.2.3.4", s.topics["subscriber1topic"].rateVisitor.ip.String())
  1841. // "Register" visitor 8.7.7.1 to topic "up012345678912" as a rate limit visitor (implicitly via topic name)
  1842. subscriber2Fn := func(r *http.Request) {
  1843. r.RemoteAddr = "8.7.7.1"
  1844. }
  1845. rr = request(t, s, "GET", "/up012345678912/json?poll=1", "", nil, subscriber2Fn)
  1846. require.Equal(t, 200, rr.Code)
  1847. require.Equal(t, "", rr.Body.String())
  1848. require.Equal(t, "8.7.7.1", s.topics["up012345678912"].rateVisitor.ip.String())
  1849. // Publish 2 messages to "subscriber1topic" as visitor 9.9.9.9. It'd be 3 normally, but the
  1850. // GET request before is also counted towards the request limiter.
  1851. for i := 0; i < 2; i++ {
  1852. rr := request(t, s, "PUT", "/subscriber1topic", "some message", nil)
  1853. require.Equal(t, 200, rr.Code)
  1854. }
  1855. rr = request(t, s, "PUT", "/subscriber1topic", "some message", nil)
  1856. require.Equal(t, 429, rr.Code)
  1857. // Publish another 2 messages to "up012345678912" as visitor 9.9.9.9
  1858. for i := 0; i < 2; i++ {
  1859. rr := request(t, s, "PUT", "/up012345678912", "some message", nil)
  1860. require.Equal(t, 200, rr.Code) // If we fail here, handlePublish is using the wrong visitor!
  1861. }
  1862. rr = request(t, s, "PUT", "/up012345678912", "some message", nil)
  1863. require.Equal(t, 429, rr.Code)
  1864. // Hurray! At this point, visitor 9.9.9.9 has published 4 messages, even though
  1865. // VisitorRequestLimitBurst is 3. That means it's working.
  1866. // Now let's confirm that so far we haven't used up any of visitor 9.9.9.9's request limiter
  1867. // by publishing another 3 requests from it.
  1868. for i := 0; i < 3; i++ {
  1869. rr := request(t, s, "PUT", "/some-other-topic", "some message", nil)
  1870. require.Equal(t, 200, rr.Code)
  1871. }
  1872. rr = request(t, s, "PUT", "/some-other-topic", "some message", nil)
  1873. require.Equal(t, 429, rr.Code)
  1874. }
  1875. func TestServer_SubscriberRateLimiting_NotEnabled_Failed(t *testing.T) {
  1876. c := newTestConfigWithAuthFile(t)
  1877. c.VisitorRequestLimitBurst = 3
  1878. c.VisitorSubscriberRateLimiting = false
  1879. s := newTestServer(t, c)
  1880. // Subscriber rate limiting is disabled!
  1881. // Registering visitor 1.2.3.4 to topic has no effect
  1882. rr := request(t, s, "GET", "/subscriber1topic/json?poll=1", "", map[string]string{
  1883. "Rate-Topics": "subscriber1topic",
  1884. }, func(r *http.Request) {
  1885. r.RemoteAddr = "1.2.3.4"
  1886. })
  1887. require.Equal(t, 200, rr.Code)
  1888. require.Equal(t, "", rr.Body.String())
  1889. require.Nil(t, s.topics["subscriber1topic"].rateVisitor)
  1890. // Registering visitor 8.7.7.1 to topic has no effect
  1891. rr = request(t, s, "GET", "/up012345678912/json?poll=1", "", nil, func(r *http.Request) {
  1892. r.RemoteAddr = "8.7.7.1"
  1893. })
  1894. require.Equal(t, 200, rr.Code)
  1895. require.Equal(t, "", rr.Body.String())
  1896. require.Nil(t, s.topics["up012345678912"].rateVisitor)
  1897. // Publish 3 messages to "subscriber1topic" as visitor 9.9.9.9
  1898. for i := 0; i < 3; i++ {
  1899. rr := request(t, s, "PUT", "/subscriber1topic", "some message", nil)
  1900. require.Equal(t, 200, rr.Code)
  1901. }
  1902. rr = request(t, s, "PUT", "/subscriber1topic", "some message", nil)
  1903. require.Equal(t, 429, rr.Code)
  1904. rr = request(t, s, "PUT", "/up012345678912", "some message", nil)
  1905. require.Equal(t, 429, rr.Code)
  1906. }
  1907. func TestServer_SubscriberRateLimiting_UP_Only(t *testing.T) {
  1908. c := newTestConfigWithAuthFile(t)
  1909. c.VisitorRequestLimitBurst = 3
  1910. c.VisitorSubscriberRateLimiting = true
  1911. s := newTestServer(t, c)
  1912. // "Register" 5 different UnifiedPush visitors
  1913. for i := 0; i < 5; i++ {
  1914. subscriberFn := func(r *http.Request) {
  1915. r.RemoteAddr = fmt.Sprintf("1.2.3.%d", i+1)
  1916. }
  1917. rr := request(t, s, "GET", fmt.Sprintf("/up12345678901%d/json?poll=1", i), "", nil, subscriberFn)
  1918. require.Equal(t, 200, rr.Code)
  1919. }
  1920. // Publish 2 messages per topic
  1921. for i := 0; i < 5; i++ {
  1922. for j := 0; j < 2; j++ {
  1923. rr := request(t, s, "PUT", fmt.Sprintf("/up12345678901%d?up=1", i), "some message", nil)
  1924. require.Equal(t, 200, rr.Code)
  1925. }
  1926. }
  1927. }
  1928. func TestServer_Matrix_SubscriberRateLimiting_UP_Only(t *testing.T) {
  1929. c := newTestConfig(t)
  1930. c.VisitorRequestLimitBurst = 3
  1931. c.VisitorSubscriberRateLimiting = true
  1932. s := newTestServer(t, c)
  1933. // "Register" 5 different UnifiedPush visitors
  1934. for i := 0; i < 5; i++ {
  1935. rr := request(t, s, "GET", fmt.Sprintf("/up12345678901%d/json?poll=1", i), "", nil, func(r *http.Request) {
  1936. r.RemoteAddr = fmt.Sprintf("1.2.3.%d", i+1)
  1937. })
  1938. require.Equal(t, 200, rr.Code)
  1939. }
  1940. // Publish 2 messages per topic
  1941. for i := 0; i < 5; i++ {
  1942. notification := fmt.Sprintf(`{"notification":{"devices":[{"pushkey":"http://127.0.0.1:12345/up12345678901%d?up=1"}]}}`, i)
  1943. for j := 0; j < 2; j++ {
  1944. response := request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1945. require.Equal(t, 200, response.Code)
  1946. require.Equal(t, `{"rejected":[]}`+"\n", response.Body.String())
  1947. }
  1948. response := request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1949. require.Equal(t, 429, response.Code, notification)
  1950. require.Equal(t, 42901, toHTTPError(t, response.Body.String()).Code)
  1951. }
  1952. }
  1953. func TestServer_SubscriberRateLimiting_VisitorExpiration(t *testing.T) {
  1954. c := newTestConfig(t)
  1955. c.VisitorRequestLimitBurst = 3
  1956. c.VisitorSubscriberRateLimiting = true
  1957. s := newTestServer(t, c)
  1958. // "Register" rate visitor
  1959. subscriberFn := func(r *http.Request) {
  1960. r.RemoteAddr = "1.2.3.4"
  1961. }
  1962. rr := request(t, s, "GET", "/mytopic/json?poll=1", "", map[string]string{
  1963. "rate-topics": "mytopic",
  1964. }, subscriberFn)
  1965. require.Equal(t, 200, rr.Code)
  1966. require.Equal(t, "1.2.3.4", s.topics["mytopic"].rateVisitor.ip.String())
  1967. require.Equal(t, s.visitors["ip:1.2.3.4"], s.topics["mytopic"].rateVisitor)
  1968. // Publish message, observe rate visitor tokens being decreased
  1969. response := request(t, s, "POST", "/mytopic", "some message", nil)
  1970. require.Equal(t, 200, response.Code)
  1971. require.Equal(t, int64(0), s.visitors["ip:9.9.9.9"].messagesLimiter.Value())
  1972. require.Equal(t, int64(1), s.topics["mytopic"].rateVisitor.messagesLimiter.Value())
  1973. require.Equal(t, s.visitors["ip:1.2.3.4"], s.topics["mytopic"].rateVisitor)
  1974. // Expire visitor
  1975. s.visitors["ip:1.2.3.4"].seen = time.Now().Add(-1 * 25 * time.Hour)
  1976. s.pruneVisitors()
  1977. // Publish message again, observe that rateVisitor is not used anymore and is reset
  1978. response = request(t, s, "POST", "/mytopic", "some message", nil)
  1979. require.Equal(t, 200, response.Code)
  1980. require.Equal(t, int64(1), s.visitors["ip:9.9.9.9"].messagesLimiter.Value())
  1981. require.Nil(t, s.topics["mytopic"].rateVisitor)
  1982. require.Nil(t, s.visitors["ip:1.2.3.4"])
  1983. }
  1984. func TestServer_SubscriberRateLimiting_ProtectedTopics(t *testing.T) {
  1985. c := newTestConfigWithAuthFile(t)
  1986. c.AuthDefault = user.PermissionDenyAll
  1987. c.VisitorSubscriberRateLimiting = true
  1988. s := newTestServer(t, c)
  1989. // Create some ACLs
  1990. require.Nil(t, s.userManager.AddTier(&user.Tier{
  1991. Code: "test",
  1992. MessageLimit: 5,
  1993. }))
  1994. require.Nil(t, s.userManager.AddUser("ben", "ben", user.RoleUser))
  1995. require.Nil(t, s.userManager.ChangeTier("ben", "test"))
  1996. require.Nil(t, s.userManager.AllowAccess("ben", "announcements", user.PermissionReadWrite))
  1997. require.Nil(t, s.userManager.AllowAccess(user.Everyone, "announcements", user.PermissionRead))
  1998. require.Nil(t, s.userManager.AllowAccess(user.Everyone, "public_topic", user.PermissionReadWrite))
  1999. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser))
  2000. require.Nil(t, s.userManager.ChangeTier("phil", "test"))
  2001. require.Nil(t, s.userManager.AddReservation("phil", "reserved-for-phil", user.PermissionReadWrite))
  2002. // Set rate visitor as user "phil" on topic
  2003. // - "reserved-for-phil": Allowed, because I am the owner
  2004. // - "public_topic": Allowed, because it has read-write permissions for everyone
  2005. // - "announcements": NOT allowed, because it has read-only permissions for everyone
  2006. rr := request(t, s, "GET", "/reserved-for-phil,public_topic,announcements/json?poll=1", "", map[string]string{
  2007. "Authorization": util.BasicAuth("phil", "phil"),
  2008. "Rate-Topics": "reserved-for-phil,public_topic,announcements",
  2009. })
  2010. require.Equal(t, 200, rr.Code)
  2011. require.Equal(t, "phil", s.topics["reserved-for-phil"].rateVisitor.user.Name)
  2012. require.Equal(t, "phil", s.topics["public_topic"].rateVisitor.user.Name)
  2013. require.Nil(t, s.topics["announcements"].rateVisitor)
  2014. // Set rate visitor as user "ben" on topic
  2015. // - "reserved-for-phil": NOT allowed, because I am not the owner
  2016. // - "public_topic": Allowed, because it has read-write permissions for everyone
  2017. // - "announcements": Allowed, because I have read-write permissions
  2018. rr = request(t, s, "GET", "/reserved-for-phil,public_topic,announcements/json?poll=1", "", map[string]string{
  2019. "Authorization": util.BasicAuth("ben", "ben"),
  2020. "Rate-Topics": "reserved-for-phil,public_topic,announcements",
  2021. })
  2022. require.Equal(t, 200, rr.Code)
  2023. require.Equal(t, "phil", s.topics["reserved-for-phil"].rateVisitor.user.Name)
  2024. require.Equal(t, "ben", s.topics["public_topic"].rateVisitor.user.Name)
  2025. require.Equal(t, "ben", s.topics["announcements"].rateVisitor.user.Name)
  2026. }
  2027. func TestServer_SubscriberRateLimiting_ProtectedTopics_WithDefaultReadWrite(t *testing.T) {
  2028. c := newTestConfigWithAuthFile(t)
  2029. c.AuthDefault = user.PermissionReadWrite
  2030. c.VisitorSubscriberRateLimiting = true
  2031. s := newTestServer(t, c)
  2032. // Create some ACLs
  2033. require.Nil(t, s.userManager.AllowAccess(user.Everyone, "announcements", user.PermissionRead))
  2034. // Set rate visitor as ip:1.2.3.4 on topic
  2035. // - "up123456789012": Allowed, because no ACLs and nobody owns the topic
  2036. // - "announcements": NOT allowed, because it has read-only permissions for everyone
  2037. rr := request(t, s, "GET", "/up123456789012,announcements/json?poll=1", "", nil, func(r *http.Request) {
  2038. r.RemoteAddr = "1.2.3.4"
  2039. })
  2040. require.Equal(t, 200, rr.Code)
  2041. require.Equal(t, "1.2.3.4", s.topics["up123456789012"].rateVisitor.ip.String())
  2042. require.Nil(t, s.topics["announcements"].rateVisitor)
  2043. }
  2044. func TestServer_MessageHistoryAndStatsEndpoint(t *testing.T) {
  2045. c := newTestConfig(t)
  2046. c.ManagerInterval = 2 * time.Second
  2047. s := newTestServer(t, c)
  2048. // Publish some messages, and get stats
  2049. for i := 0; i < 5; i++ {
  2050. response := request(t, s, "POST", "/mytopic", "some message", nil)
  2051. require.Equal(t, 200, response.Code)
  2052. }
  2053. require.Equal(t, int64(5), s.messages)
  2054. require.Equal(t, []int64{0}, s.messagesHistory)
  2055. response := request(t, s, "GET", "/v1/stats", "", nil)
  2056. require.Equal(t, 200, response.Code)
  2057. require.Equal(t, `{"messages":5,"messages_rate":0}`+"\n", response.Body.String())
  2058. // Run manager and see message history update
  2059. s.execManager()
  2060. require.Equal(t, []int64{0, 5}, s.messagesHistory)
  2061. response = request(t, s, "GET", "/v1/stats", "", nil)
  2062. require.Equal(t, 200, response.Code)
  2063. require.Equal(t, `{"messages":5,"messages_rate":2.5}`+"\n", response.Body.String()) // 5 messages in 2 seconds = 2.5 messages per second
  2064. // Publish some more messages
  2065. for i := 0; i < 10; i++ {
  2066. response := request(t, s, "POST", "/mytopic", "some message", nil)
  2067. require.Equal(t, 200, response.Code)
  2068. }
  2069. require.Equal(t, int64(15), s.messages)
  2070. require.Equal(t, []int64{0, 5}, s.messagesHistory)
  2071. response = request(t, s, "GET", "/v1/stats", "", nil)
  2072. require.Equal(t, 200, response.Code)
  2073. require.Equal(t, `{"messages":15,"messages_rate":2.5}`+"\n", response.Body.String()) // Rate did not update yet
  2074. // Run manager and see message history update
  2075. s.execManager()
  2076. require.Equal(t, []int64{0, 5, 15}, s.messagesHistory)
  2077. response = request(t, s, "GET", "/v1/stats", "", nil)
  2078. require.Equal(t, 200, response.Code)
  2079. require.Equal(t, `{"messages":15,"messages_rate":3.75}`+"\n", response.Body.String()) // 15 messages in 4 seconds = 3.75 messages per second
  2080. }
  2081. func TestServer_MessageHistoryMaxSize(t *testing.T) {
  2082. s := newTestServer(t, newTestConfig(t))
  2083. for i := 0; i < 20; i++ {
  2084. s.messages = int64(i)
  2085. s.execManager()
  2086. }
  2087. require.Equal(t, []int64{10, 11, 12, 13, 14, 15, 16, 17, 18, 19}, s.messagesHistory)
  2088. }
  2089. func TestServer_MessageCountPersistence(t *testing.T) {
  2090. c := newTestConfig(t)
  2091. s := newTestServer(t, c)
  2092. s.messages = 1234
  2093. s.execManager()
  2094. waitFor(t, func() bool {
  2095. messages, err := s.messageCache.Stats()
  2096. require.Nil(t, err)
  2097. return messages == 1234
  2098. })
  2099. s = newTestServer(t, c)
  2100. require.Equal(t, int64(1234), s.messages)
  2101. }
  2102. func TestServer_PublishWithUTF8MimeHeader(t *testing.T) {
  2103. s := newTestServer(t, newTestConfig(t))
  2104. response := request(t, s, "POST", "/mytopic", "some attachment", map[string]string{
  2105. "X-Filename": "some =?UTF-8?q?=C3=A4?=ttachment.txt",
  2106. "X-Message": "=?UTF-8?B?8J+HqfCfh6o=?=",
  2107. "X-Title": "=?UTF-8?B?bnRmeSDlvojmo5I=?=, no really I mean it! =?UTF-8?Q?This is q=C3=BC=C3=B6ted-print=C3=A4ble.?=",
  2108. "X-Tags": "=?UTF-8?B?8J+HqfCfh6o=?=, =?UTF-8?B?bnRmeSDlvojmo5I=?=",
  2109. "X-Click": "=?uTf-8?b?aHR0cHM6Ly/wn5KpLmxh?=",
  2110. "X-Actions": "http, \"=?utf-8?q?Mettre =C3=A0 jour?=\", \"https://my.tld/webhook/netbird-update\"; =?utf-8?b?aHR0cCwg6L+Z5piv5LiA5Liq5qCH562+LCBodHRwczovL/CfkqkubGE=?=",
  2111. })
  2112. require.Equal(t, 200, response.Code)
  2113. m := toMessage(t, response.Body.String())
  2114. require.Equal(t, "🇩🇪", m.Message)
  2115. require.Equal(t, "ntfy 很棒, no really I mean it! This is qüöted-printäble.", m.Title)
  2116. require.Equal(t, "some ättachment.txt", m.Attachment.Name)
  2117. require.Equal(t, "🇩🇪", m.Tags[0])
  2118. require.Equal(t, "ntfy 很棒", m.Tags[1])
  2119. require.Equal(t, "https://💩.la", m.Click)
  2120. require.Equal(t, "Mettre à jour", m.Actions[0].Label)
  2121. require.Equal(t, "http", m.Actions[1].Action)
  2122. require.Equal(t, "这是一个标签", m.Actions[1].Label)
  2123. require.Equal(t, "https://💩.la", m.Actions[1].URL)
  2124. }
  2125. func TestServer_UpstreamBaseURL_Success(t *testing.T) {
  2126. var pollID atomic.Pointer[string]
  2127. upstreamServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  2128. body, err := io.ReadAll(r.Body)
  2129. require.Nil(t, err)
  2130. require.Equal(t, "/87c9cddf7b0105f5fe849bf084c6e600be0fde99be3223335199b4965bd7b735", r.URL.Path)
  2131. require.Equal(t, "", string(body))
  2132. require.NotEmpty(t, r.Header.Get("X-Poll-ID"))
  2133. pollID.Store(util.String(r.Header.Get("X-Poll-ID")))
  2134. }))
  2135. defer upstreamServer.Close()
  2136. c := newTestConfigWithAuthFile(t)
  2137. c.BaseURL = "http://myserver.internal"
  2138. c.UpstreamBaseURL = upstreamServer.URL
  2139. s := newTestServer(t, c)
  2140. // Send message, and wait for upstream server to receive it
  2141. response := request(t, s, "PUT", "/mytopic", `hi there`, nil)
  2142. require.Equal(t, 200, response.Code)
  2143. m := toMessage(t, response.Body.String())
  2144. require.NotEmpty(t, m.ID)
  2145. require.Equal(t, "hi there", m.Message)
  2146. waitFor(t, func() bool {
  2147. pID := pollID.Load()
  2148. return pID != nil && *pID == m.ID
  2149. })
  2150. }
  2151. func TestServer_UpstreamBaseURL_With_Access_Token_Success(t *testing.T) {
  2152. var pollID atomic.Pointer[string]
  2153. upstreamServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  2154. body, err := io.ReadAll(r.Body)
  2155. require.Nil(t, err)
  2156. require.Equal(t, "/a1c72bcb4daf5af54d13ef86aea8f76c11e8b88320d55f1811d5d7b173bcc1df", r.URL.Path)
  2157. require.Equal(t, "Bearer tk_1234567890", r.Header.Get("Authorization"))
  2158. require.Equal(t, "", string(body))
  2159. require.NotEmpty(t, r.Header.Get("X-Poll-ID"))
  2160. pollID.Store(util.String(r.Header.Get("X-Poll-ID")))
  2161. }))
  2162. defer upstreamServer.Close()
  2163. c := newTestConfigWithAuthFile(t)
  2164. c.BaseURL = "http://myserver.internal"
  2165. c.UpstreamBaseURL = upstreamServer.URL
  2166. c.UpstreamAccessToken = "tk_1234567890"
  2167. s := newTestServer(t, c)
  2168. // Send message, and wait for upstream server to receive it
  2169. response := request(t, s, "PUT", "/mytopic1", `hi there`, nil)
  2170. require.Equal(t, 200, response.Code)
  2171. m := toMessage(t, response.Body.String())
  2172. require.NotEmpty(t, m.ID)
  2173. require.Equal(t, "hi there", m.Message)
  2174. waitFor(t, func() bool {
  2175. pID := pollID.Load()
  2176. return pID != nil && *pID == m.ID
  2177. })
  2178. }
  2179. func TestServer_UpstreamBaseURL_DoNotForwardUnifiedPush(t *testing.T) {
  2180. upstreamServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  2181. t.Fatal("UnifiedPush messages should not be forwarded")
  2182. }))
  2183. defer upstreamServer.Close()
  2184. c := newTestConfigWithAuthFile(t)
  2185. c.BaseURL = "http://myserver.internal"
  2186. c.UpstreamBaseURL = upstreamServer.URL
  2187. s := newTestServer(t, c)
  2188. // Send UP message, this should not forward to upstream server
  2189. response := request(t, s, "PUT", "/mytopic?up=1", `hi there`, nil)
  2190. require.Equal(t, 200, response.Code)
  2191. m := toMessage(t, response.Body.String())
  2192. require.NotEmpty(t, m.ID)
  2193. require.Equal(t, "hi there", m.Message)
  2194. // Forwarding is done asynchronously, so wait a bit.
  2195. // This ensures that the t.Fatal above is actually not triggered.
  2196. time.Sleep(500 * time.Millisecond)
  2197. }
  2198. func newTestConfig(t *testing.T) *Config {
  2199. conf := NewConfig()
  2200. conf.BaseURL = "http://127.0.0.1:12345"
  2201. conf.CacheFile = filepath.Join(t.TempDir(), "cache.db")
  2202. conf.CacheStartupQueries = "pragma journal_mode = WAL; pragma synchronous = normal; pragma temp_store = memory;"
  2203. conf.AttachmentCacheDir = t.TempDir()
  2204. return conf
  2205. }
  2206. func newTestConfigWithAuthFile(t *testing.T) *Config {
  2207. conf := newTestConfig(t)
  2208. conf.AuthFile = filepath.Join(t.TempDir(), "user.db")
  2209. conf.AuthStartupQueries = "pragma journal_mode = WAL; pragma synchronous = normal; pragma temp_store = memory;"
  2210. conf.AuthBcryptCost = bcrypt.MinCost // This speeds up tests a lot
  2211. return conf
  2212. }
  2213. func newTestServer(t *testing.T, config *Config) *Server {
  2214. server, err := New(config)
  2215. if err != nil {
  2216. t.Fatal(err)
  2217. }
  2218. return server
  2219. }
  2220. func request(t *testing.T, s *Server, method, url, body string, headers map[string]string, fn ...func(r *http.Request)) *httptest.ResponseRecorder {
  2221. rr := httptest.NewRecorder()
  2222. r, err := http.NewRequest(method, url, strings.NewReader(body))
  2223. if err != nil {
  2224. t.Fatal(err)
  2225. }
  2226. r.RemoteAddr = "9.9.9.9" // Used for tests
  2227. for k, v := range headers {
  2228. r.Header.Set(k, v)
  2229. }
  2230. for _, f := range fn {
  2231. f(r)
  2232. }
  2233. s.handle(rr, r)
  2234. return rr
  2235. }
  2236. func subscribe(t *testing.T, s *Server, url string, rr *httptest.ResponseRecorder) context.CancelFunc {
  2237. ctx, cancel := context.WithCancel(context.Background())
  2238. req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
  2239. if err != nil {
  2240. t.Fatal(err)
  2241. }
  2242. done := make(chan bool)
  2243. go func() {
  2244. s.handle(rr, req)
  2245. done <- true
  2246. }()
  2247. cancelAndWaitForDone := func() {
  2248. time.Sleep(200 * time.Millisecond)
  2249. cancel()
  2250. <-done
  2251. }
  2252. time.Sleep(200 * time.Millisecond)
  2253. return cancelAndWaitForDone
  2254. }
  2255. func toMessages(t *testing.T, s string) []*message {
  2256. messages := make([]*message, 0)
  2257. scanner := bufio.NewScanner(strings.NewReader(s))
  2258. for scanner.Scan() {
  2259. messages = append(messages, toMessage(t, scanner.Text()))
  2260. }
  2261. return messages
  2262. }
  2263. func toMessage(t *testing.T, s string) *message {
  2264. var m message
  2265. require.Nil(t, json.NewDecoder(strings.NewReader(s)).Decode(&m))
  2266. return &m
  2267. }
  2268. func toHTTPError(t *testing.T, s string) *errHTTP {
  2269. var e errHTTP
  2270. require.Nil(t, json.NewDecoder(strings.NewReader(s)).Decode(&e))
  2271. return &e
  2272. }
  2273. func readAll(t *testing.T, rc io.ReadCloser) string {
  2274. b, err := io.ReadAll(rc)
  2275. if err != nil {
  2276. t.Fatal(err)
  2277. }
  2278. return string(b)
  2279. }
  2280. func waitFor(t *testing.T, f func() bool) {
  2281. waitForWithMaxWait(t, 5*time.Second, f)
  2282. }
  2283. func waitForWithMaxWait(t *testing.T, maxWait time.Duration, f func() bool) {
  2284. start := time.Now()
  2285. for time.Since(start) < maxWait {
  2286. if f() {
  2287. return
  2288. }
  2289. time.Sleep(50 * time.Millisecond)
  2290. }
  2291. t.Fatalf("Function f did not succeed after %v: %v", maxWait, string(debug.Stack()))
  2292. }