server_test.go 100 KB

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