server_test.go 101 KB

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