server_test.go 168 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424
  1. package server
  2. import (
  3. "bufio"
  4. "context"
  5. "crypto/rand"
  6. _ "embed"
  7. "encoding/base64"
  8. "encoding/json"
  9. "fmt"
  10. "golang.org/x/crypto/bcrypt"
  11. "heckel.io/ntfy/v2/user"
  12. "io"
  13. "net/http"
  14. "net/http/httptest"
  15. "net/netip"
  16. "os"
  17. "path/filepath"
  18. "runtime/debug"
  19. "strings"
  20. "sync"
  21. "sync/atomic"
  22. "testing"
  23. "time"
  24. "github.com/SherClockHolmes/webpush-go"
  25. "github.com/stretchr/testify/require"
  26. "heckel.io/ntfy/v2/log"
  27. "heckel.io/ntfy/v2/util"
  28. )
  29. func TestMain(m *testing.M) {
  30. log.SetLevel(log.ErrorLevel)
  31. os.Exit(m.Run())
  32. }
  33. func TestServer_PublishAndPoll(t *testing.T) {
  34. s := newTestServer(t, newTestConfig(t))
  35. response1 := request(t, s, "PUT", "/mytopic", "my first message", nil)
  36. msg1 := toMessage(t, response1.Body.String())
  37. require.NotEmpty(t, msg1.ID)
  38. require.Equal(t, "my first message", msg1.Message)
  39. response2 := request(t, s, "PUT", "/mytopic", "my second\n\nmessage", nil)
  40. msg2 := toMessage(t, response2.Body.String())
  41. require.NotEqual(t, msg1.ID, msg2.ID)
  42. require.NotEmpty(t, msg2.ID)
  43. require.Equal(t, "my second\n\nmessage", msg2.Message)
  44. response := request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  45. messages := toMessages(t, response.Body.String())
  46. require.Equal(t, 2, len(messages))
  47. require.Equal(t, "my first message", messages[0].Message)
  48. require.Equal(t, "my second\n\nmessage", messages[1].Message)
  49. response = request(t, s, "GET", "/mytopic/sse?poll=1&since=all", "", nil)
  50. lines := strings.Split(strings.TrimSpace(response.Body.String()), "\n")
  51. require.Equal(t, 3, len(lines))
  52. require.Equal(t, "my first message", toMessage(t, strings.TrimPrefix(lines[0], "data: ")).Message)
  53. require.Equal(t, "", lines[1])
  54. require.Equal(t, "my second\n\nmessage", toMessage(t, strings.TrimPrefix(lines[2], "data: ")).Message)
  55. response = request(t, s, "GET", "/mytopic/raw?poll=1", "", nil)
  56. lines = strings.Split(strings.TrimSpace(response.Body.String()), "\n")
  57. require.Equal(t, 2, len(lines))
  58. require.Equal(t, "my first message", lines[0])
  59. require.Equal(t, "my second message", lines[1]) // \n -> " "
  60. }
  61. func TestServer_PublishWithFirebase(t *testing.T) {
  62. sender := newTestFirebaseSender(10)
  63. s := newTestServer(t, newTestConfig(t))
  64. s.firebaseClient = newFirebaseClient(sender, &testAuther{Allow: true})
  65. response := request(t, s, "PUT", "/mytopic", "my first message", nil)
  66. msg1 := toMessage(t, response.Body.String())
  67. require.NotEmpty(t, msg1.ID)
  68. require.Equal(t, "my first message", msg1.Message)
  69. time.Sleep(100 * time.Millisecond) // Firebase publishing happens
  70. require.Equal(t, 1, len(sender.Messages()))
  71. require.Equal(t, "my first message", sender.Messages()[0].Data["message"])
  72. require.Equal(t, "my first message", sender.Messages()[0].APNS.Payload.Aps.Alert.Body)
  73. require.Equal(t, "my first message", sender.Messages()[0].APNS.Payload.CustomData["message"])
  74. }
  75. func TestServer_PublishWithoutFirebase(t *testing.T) {
  76. sender := newTestFirebaseSender(10)
  77. s := newTestServer(t, newTestConfig(t))
  78. s.firebaseClient = newFirebaseClient(sender, &testAuther{Allow: true})
  79. response := request(t, s, "PUT", "/mytopic", "my first message", map[string]string{
  80. "firebase": "no",
  81. })
  82. msg1 := toMessage(t, response.Body.String())
  83. require.NotEmpty(t, msg1.ID)
  84. require.Equal(t, "my first message", msg1.Message)
  85. time.Sleep(100 * time.Millisecond) // Firebase publishing happens
  86. require.Equal(t, 0, len(sender.Messages()))
  87. }
  88. func TestServer_PublishWithFirebase_WithoutUsers_AndWithoutPanic(t *testing.T) {
  89. // This tests issue #641, which used to panic before the fix
  90. firebaseKeyFile := filepath.Join(t.TempDir(), "firebase.json")
  91. contents := `{
  92. "type": "service_account",
  93. "project_id": "ntfy-test",
  94. "private_key_id": "fsfhskjdfhskdhfskdjfhsdf",
  95. "private_key": "lalala",
  96. "client_email": "firebase-adminsdk-muv04@ntfy-test.iam.gserviceaccount.com",
  97. "client_id": "123123213",
  98. "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  99. "token_uri": "https://oauth2.googleapis.com/token",
  100. "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  101. "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-muv04%40ntfy-test.iam.gserviceaccount.com"
  102. }
  103. `
  104. require.Nil(t, os.WriteFile(firebaseKeyFile, []byte(contents), 0600))
  105. c := newTestConfig(t)
  106. c.FirebaseKeyFile = firebaseKeyFile
  107. s := newTestServer(t, c)
  108. response := request(t, s, "PUT", "/mytopic", "my first message", nil)
  109. require.Equal(t, "my first message", toMessage(t, response.Body.String()).Message)
  110. }
  111. func TestServer_SubscribeOpenAndKeepalive(t *testing.T) {
  112. t.Parallel()
  113. c := newTestConfig(t)
  114. c.KeepaliveInterval = time.Second
  115. s := newTestServer(t, c)
  116. rr := httptest.NewRecorder()
  117. ctx, cancel := context.WithCancel(context.Background())
  118. req, err := http.NewRequestWithContext(ctx, "GET", "/mytopic/json", nil)
  119. if err != nil {
  120. t.Fatal(err)
  121. }
  122. doneChan := make(chan bool)
  123. go func() {
  124. s.handle(rr, req)
  125. doneChan <- true
  126. }()
  127. time.Sleep(1300 * time.Millisecond)
  128. cancel()
  129. <-doneChan
  130. messages := toMessages(t, rr.Body.String())
  131. require.Equal(t, 2, len(messages))
  132. require.Equal(t, openEvent, messages[0].Event)
  133. require.Equal(t, "mytopic", messages[0].Topic)
  134. require.Equal(t, "", messages[0].Message)
  135. require.Equal(t, "", messages[0].Title)
  136. require.Equal(t, 0, messages[0].Priority)
  137. require.Nil(t, messages[0].Tags)
  138. require.Equal(t, keepaliveEvent, messages[1].Event)
  139. require.Equal(t, "mytopic", messages[1].Topic)
  140. require.Equal(t, "", messages[1].Message)
  141. require.Equal(t, "", messages[1].Title)
  142. require.Equal(t, 0, messages[1].Priority)
  143. require.Nil(t, messages[1].Tags)
  144. }
  145. func TestServer_PublishAndSubscribe(t *testing.T) {
  146. t.Parallel()
  147. s := newTestServer(t, newTestConfig(t))
  148. subscribeRR := httptest.NewRecorder()
  149. subscribeCancel := subscribe(t, s, "/mytopic/json", subscribeRR)
  150. publishFirstRR := request(t, s, "PUT", "/mytopic", "my first message", nil)
  151. require.Equal(t, 200, publishFirstRR.Code)
  152. time.Sleep(500 * time.Millisecond) // Publishing is done asynchronously, this avoids races
  153. publishSecondRR := request(t, s, "PUT", "/mytopic", "my other message", map[string]string{
  154. "Title": " This is a title ",
  155. "X-Tags": "tag1,tag 2, tag3",
  156. "p": "1",
  157. })
  158. require.Equal(t, 200, publishSecondRR.Code)
  159. subscribeCancel()
  160. messages := toMessages(t, subscribeRR.Body.String())
  161. require.Equal(t, 3, len(messages))
  162. require.Equal(t, openEvent, messages[0].Event)
  163. require.Equal(t, messageEvent, messages[1].Event)
  164. require.Equal(t, "mytopic", messages[1].Topic)
  165. require.Equal(t, "my first message", messages[1].Message)
  166. require.Equal(t, "", messages[1].Title)
  167. require.Equal(t, 0, messages[1].Priority)
  168. require.Nil(t, messages[1].Tags)
  169. require.True(t, time.Now().Add(12*time.Hour-5*time.Second).Unix() < messages[1].Expires)
  170. require.True(t, time.Now().Add(12*time.Hour+5*time.Second).Unix() > messages[1].Expires)
  171. require.Equal(t, messageEvent, messages[2].Event)
  172. require.Equal(t, "mytopic", messages[2].Topic)
  173. require.Equal(t, "my other message", messages[2].Message)
  174. require.Equal(t, "This is a title", messages[2].Title)
  175. require.Equal(t, 1, messages[2].Priority)
  176. require.Equal(t, []string{"tag1", "tag 2", "tag3"}, messages[2].Tags)
  177. }
  178. func TestServer_Publish_Disallowed_Topic(t *testing.T) {
  179. c := newTestConfig(t)
  180. c.DisallowedTopics = []string{"about", "time", "this", "got", "added"}
  181. s := newTestServer(t, c)
  182. rr := request(t, s, "PUT", "/mytopic", "my first message", nil)
  183. require.Equal(t, 200, rr.Code)
  184. rr = request(t, s, "PUT", "/about", "another message", nil)
  185. require.Equal(t, 400, rr.Code)
  186. require.Equal(t, 40010, toHTTPError(t, rr.Body.String()).Code)
  187. }
  188. func TestServer_StaticSites(t *testing.T) {
  189. s := newTestServer(t, newTestConfig(t))
  190. rr := request(t, s, "GET", "/", "", nil)
  191. require.Equal(t, 200, rr.Code)
  192. require.Contains(t, rr.Body.String(), "</html>")
  193. rr = request(t, s, "HEAD", "/", "", nil)
  194. require.Equal(t, 200, rr.Code)
  195. rr = request(t, s, "OPTIONS", "/", "", nil)
  196. require.Equal(t, 200, rr.Code)
  197. rr = request(t, s, "GET", "/does-not-exist.txt", "", nil)
  198. require.Equal(t, 404, rr.Code)
  199. rr = request(t, s, "GET", "/mytopic", "", nil)
  200. require.Equal(t, 200, rr.Code)
  201. require.Contains(t, rr.Body.String(), `<meta name="robots" content="noindex, nofollow" />`)
  202. rr = request(t, s, "GET", "/docs", "", nil)
  203. require.Equal(t, 301, rr.Code)
  204. // Docs test removed, it was failing annoyingly.
  205. }
  206. func TestServer_WebEnabled(t *testing.T) {
  207. conf := newTestConfig(t)
  208. conf.WebRoot = "" // Disable web app
  209. s := newTestServer(t, conf)
  210. rr := request(t, s, "GET", "/", "", nil)
  211. require.Equal(t, 404, rr.Code)
  212. rr = request(t, s, "GET", "/config.js", "", nil)
  213. require.Equal(t, 404, rr.Code)
  214. rr = request(t, s, "GET", "/sw.js", "", nil)
  215. require.Equal(t, 404, rr.Code)
  216. rr = request(t, s, "GET", "/app.html", "", nil)
  217. require.Equal(t, 404, rr.Code)
  218. rr = request(t, s, "GET", "/static/css/home.css", "", nil)
  219. require.Equal(t, 404, rr.Code)
  220. conf2 := newTestConfig(t)
  221. conf2.WebRoot = "/"
  222. s2 := newTestServer(t, conf2)
  223. rr = request(t, s2, "GET", "/", "", nil)
  224. require.Equal(t, 200, rr.Code)
  225. rr = request(t, s2, "GET", "/config.js", "", nil)
  226. require.Equal(t, 200, rr.Code)
  227. rr = request(t, s2, "GET", "/sw.js", "", nil)
  228. require.Equal(t, 200, rr.Code)
  229. rr = request(t, s2, "GET", "/app.html", "", nil)
  230. require.Equal(t, 200, rr.Code)
  231. }
  232. func TestServer_WebPushEnabled(t *testing.T) {
  233. conf := newTestConfig(t)
  234. conf.WebRoot = "" // Disable web app
  235. s := newTestServer(t, conf)
  236. rr := request(t, s, "GET", "/manifest.webmanifest", "", nil)
  237. require.Equal(t, 404, rr.Code)
  238. conf2 := newTestConfig(t)
  239. s2 := newTestServer(t, conf2)
  240. rr = request(t, s2, "GET", "/manifest.webmanifest", "", nil)
  241. require.Equal(t, 404, rr.Code)
  242. conf3 := newTestConfigWithWebPush(t)
  243. s3 := newTestServer(t, conf3)
  244. rr = request(t, s3, "GET", "/manifest.webmanifest", "", nil)
  245. require.Equal(t, 200, rr.Code)
  246. require.Equal(t, "application/manifest+json", rr.Header().Get("Content-Type"))
  247. }
  248. func TestServer_PublishLargeMessage(t *testing.T) {
  249. c := newTestConfig(t)
  250. c.AttachmentCacheDir = "" // Disable attachments
  251. s := newTestServer(t, c)
  252. body := strings.Repeat("this is a large message", 5000)
  253. response := request(t, s, "PUT", "/mytopic", body, nil)
  254. require.Equal(t, 400, response.Code)
  255. }
  256. func TestServer_PublishPriority(t *testing.T) {
  257. s := newTestServer(t, newTestConfig(t))
  258. for prio := 1; prio <= 5; prio++ {
  259. response := request(t, s, "GET", fmt.Sprintf("/mytopic/publish?priority=%d", prio), fmt.Sprintf("priority %d", prio), nil)
  260. msg := toMessage(t, response.Body.String())
  261. require.Equal(t, prio, msg.Priority)
  262. }
  263. response := request(t, s, "GET", "/mytopic/publish?priority=min", "test", nil)
  264. require.Equal(t, 1, toMessage(t, response.Body.String()).Priority)
  265. response = request(t, s, "GET", "/mytopic/send?priority=low", "test", nil)
  266. require.Equal(t, 2, toMessage(t, response.Body.String()).Priority)
  267. response = request(t, s, "GET", "/mytopic/send?priority=default", "test", nil)
  268. require.Equal(t, 3, toMessage(t, response.Body.String()).Priority)
  269. response = request(t, s, "GET", "/mytopic/send?priority=high", "test", nil)
  270. require.Equal(t, 4, toMessage(t, response.Body.String()).Priority)
  271. response = request(t, s, "GET", "/mytopic/send?priority=max", "test", nil)
  272. require.Equal(t, 5, toMessage(t, response.Body.String()).Priority)
  273. response = request(t, s, "GET", "/mytopic/trigger?priority=urgent", "test", nil)
  274. require.Equal(t, 5, toMessage(t, response.Body.String()).Priority)
  275. response = request(t, s, "GET", "/mytopic/trigger?priority=INVALID", "test", nil)
  276. require.Equal(t, 40007, toHTTPError(t, response.Body.String()).Code)
  277. }
  278. func TestServer_PublishPriority_SpecialHTTPHeader(t *testing.T) {
  279. s := newTestServer(t, newTestConfig(t))
  280. response := request(t, s, "POST", "/mytopic", "test", map[string]string{
  281. "Priority": "u=4",
  282. "X-Priority": "5",
  283. })
  284. require.Equal(t, 5, toMessage(t, response.Body.String()).Priority)
  285. response = request(t, s, "POST", "/mytopic?priority=4", "test", map[string]string{
  286. "Priority": "u=9",
  287. })
  288. require.Equal(t, 4, toMessage(t, response.Body.String()).Priority)
  289. response = request(t, s, "POST", "/mytopic", "test", map[string]string{
  290. "p": "2",
  291. "priority": "u=9, i",
  292. })
  293. require.Equal(t, 2, toMessage(t, response.Body.String()).Priority)
  294. }
  295. func TestServer_PublishGETOnlyOneTopic(t *testing.T) {
  296. // This tests a bug that allowed publishing topics with a comma in the name (no ticket)
  297. s := newTestServer(t, newTestConfig(t))
  298. response := request(t, s, "GET", "/mytopic,mytopic2/publish?m=hi", "", nil)
  299. require.Equal(t, 404, response.Code)
  300. }
  301. func TestServer_PublishNoCache(t *testing.T) {
  302. s := newTestServer(t, newTestConfig(t))
  303. response := request(t, s, "PUT", "/mytopic", "this message is not cached", map[string]string{
  304. "Cache": "no",
  305. })
  306. msg := toMessage(t, response.Body.String())
  307. require.NotEmpty(t, msg.ID)
  308. require.Equal(t, "this message is not cached", msg.Message)
  309. require.Equal(t, int64(0), msg.Expires)
  310. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  311. messages := toMessages(t, response.Body.String())
  312. require.Empty(t, messages)
  313. }
  314. func TestServer_PublishAt(t *testing.T) {
  315. t.Parallel()
  316. s := newTestServer(t, newTestConfig(t))
  317. response := request(t, s, "PUT", "/mytopic", "a message", map[string]string{
  318. "In": "1h",
  319. })
  320. require.Equal(t, 200, response.Code)
  321. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  322. messages := toMessages(t, response.Body.String())
  323. require.Equal(t, 0, len(messages))
  324. // Update message time to the past
  325. fakeTime := time.Now().Add(-10 * time.Second).Unix()
  326. _, err := s.messageCache.db.Exec(`UPDATE messages SET time=?`, fakeTime)
  327. require.Nil(t, err)
  328. // Trigger delayed message sending
  329. require.Nil(t, s.sendDelayedMessages())
  330. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  331. messages = toMessages(t, response.Body.String())
  332. require.Equal(t, 1, len(messages))
  333. require.Equal(t, "a message", messages[0].Message)
  334. require.Equal(t, netip.Addr{}, messages[0].Sender) // Never return the sender!
  335. messages, err = s.messageCache.Messages("mytopic", sinceAllMessages, true)
  336. require.Nil(t, err)
  337. require.Equal(t, 1, len(messages))
  338. require.Equal(t, "a message", messages[0].Message)
  339. require.Equal(t, "9.9.9.9", messages[0].Sender.String()) // It's stored in the DB though!
  340. }
  341. func TestServer_PublishAt_FromUser(t *testing.T) {
  342. t.Parallel()
  343. s := newTestServer(t, newTestConfigWithAuthFile(t))
  344. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleAdmin, false))
  345. response := request(t, s, "PUT", "/mytopic", "a message", map[string]string{
  346. "Authorization": util.BasicAuth("phil", "phil"),
  347. "In": "1h",
  348. })
  349. require.Equal(t, 200, response.Code)
  350. // Message doesn't show up immediately
  351. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  352. messages := toMessages(t, response.Body.String())
  353. require.Equal(t, 0, len(messages))
  354. // Update message time to the past
  355. fakeTime := time.Now().Add(-10 * time.Second).Unix()
  356. _, err := s.messageCache.db.Exec(`UPDATE messages SET time=?`, fakeTime)
  357. require.Nil(t, err)
  358. // Trigger delayed message sending
  359. require.Nil(t, s.sendDelayedMessages())
  360. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  361. messages = toMessages(t, response.Body.String())
  362. require.Equal(t, 1, len(messages))
  363. require.Equal(t, fakeTime, messages[0].Time)
  364. require.Equal(t, "a message", messages[0].Message)
  365. messages, err = s.messageCache.Messages("mytopic", sinceAllMessages, true)
  366. require.Nil(t, err)
  367. require.Equal(t, 1, len(messages))
  368. require.Equal(t, "a message", messages[0].Message)
  369. require.True(t, strings.HasPrefix(messages[0].User, "u_"))
  370. }
  371. func TestServer_PublishAt_Expires(t *testing.T) {
  372. s := newTestServer(t, newTestConfig(t))
  373. response := request(t, s, "PUT", "/mytopic", "a message", map[string]string{
  374. "In": "2 days",
  375. })
  376. require.Equal(t, 200, response.Code)
  377. m := toMessage(t, response.Body.String())
  378. require.True(t, m.Expires > time.Now().Add(12*time.Hour+48*time.Hour-time.Minute).Unix())
  379. require.True(t, m.Expires < time.Now().Add(12*time.Hour+48*time.Hour+time.Minute).Unix())
  380. }
  381. func TestServer_PublishAtWithCacheError(t *testing.T) {
  382. s := newTestServer(t, newTestConfig(t))
  383. response := request(t, s, "PUT", "/mytopic", "a message", map[string]string{
  384. "Cache": "no",
  385. "In": "30 min",
  386. })
  387. require.Equal(t, 400, response.Code)
  388. require.Equal(t, errHTTPBadRequestDelayNoCache, toHTTPError(t, response.Body.String()))
  389. }
  390. func TestServer_PublishAtTooShortDelay(t *testing.T) {
  391. s := newTestServer(t, newTestConfig(t))
  392. response := request(t, s, "PUT", "/mytopic", "a message", map[string]string{
  393. "In": "1s",
  394. })
  395. require.Equal(t, 400, response.Code)
  396. }
  397. func TestServer_PublishAtTooLongDelay(t *testing.T) {
  398. s := newTestServer(t, newTestConfig(t))
  399. response := request(t, s, "PUT", "/mytopic", "a message", map[string]string{
  400. "In": "99999999h",
  401. })
  402. require.Equal(t, 400, response.Code)
  403. }
  404. func TestServer_PublishAtInvalidDelay(t *testing.T) {
  405. s := newTestServer(t, newTestConfig(t))
  406. response := request(t, s, "PUT", "/mytopic?delay=INVALID", "a message", nil)
  407. err := toHTTPError(t, response.Body.String())
  408. require.Equal(t, 400, response.Code)
  409. require.Equal(t, 40004, err.Code)
  410. }
  411. func TestServer_PublishAtTooLarge(t *testing.T) {
  412. s := newTestServer(t, newTestConfig(t))
  413. response := request(t, s, "PUT", "/mytopic?x-in=99999h", "a message", nil)
  414. err := toHTTPError(t, response.Body.String())
  415. require.Equal(t, 400, response.Code)
  416. require.Equal(t, 40006, err.Code)
  417. }
  418. func TestServer_PublishAtAndPrune(t *testing.T) {
  419. s := newTestServer(t, newTestConfig(t))
  420. response := request(t, s, "PUT", "/mytopic", "a message", map[string]string{
  421. "In": "1h",
  422. })
  423. require.Equal(t, 200, response.Code)
  424. s.execManager() // Fire pruning
  425. response = request(t, s, "GET", "/mytopic/json?poll=1&scheduled=1", "", nil)
  426. messages := toMessages(t, response.Body.String())
  427. require.Equal(t, 1, len(messages)) // Not affected by pruning
  428. require.Equal(t, "a message", messages[0].Message)
  429. time.Sleep(time.Second) // FIXME CI failing not sure why
  430. }
  431. func TestServer_PublishAndMultiPoll(t *testing.T) {
  432. s := newTestServer(t, newTestConfig(t))
  433. response := request(t, s, "PUT", "/mytopic1", "message 1", nil)
  434. msg := toMessage(t, response.Body.String())
  435. require.NotEmpty(t, msg.ID)
  436. require.Equal(t, "mytopic1", msg.Topic)
  437. require.Equal(t, "message 1", msg.Message)
  438. response = request(t, s, "PUT", "/mytopic2", "message 2", nil)
  439. msg = toMessage(t, response.Body.String())
  440. require.NotEmpty(t, msg.ID)
  441. require.Equal(t, "mytopic2", msg.Topic)
  442. require.Equal(t, "message 2", msg.Message)
  443. response = request(t, s, "GET", "/mytopic1/json?poll=1", "", nil)
  444. messages := toMessages(t, response.Body.String())
  445. require.Equal(t, 1, len(messages))
  446. require.Equal(t, "mytopic1", messages[0].Topic)
  447. require.Equal(t, "message 1", messages[0].Message)
  448. response = request(t, s, "GET", "/mytopic1,mytopic2/json?poll=1", "", nil)
  449. messages = toMessages(t, response.Body.String())
  450. require.Equal(t, 2, len(messages))
  451. require.Equal(t, "mytopic1", messages[0].Topic)
  452. require.Equal(t, "message 1", messages[0].Message)
  453. require.Equal(t, "mytopic2", messages[1].Topic)
  454. require.Equal(t, "message 2", messages[1].Message)
  455. }
  456. func TestServer_PublishWithNopCache(t *testing.T) {
  457. c := newTestConfig(t)
  458. c.CacheDuration = 0
  459. s := newTestServer(t, c)
  460. subscribeRR := httptest.NewRecorder()
  461. subscribeCancel := subscribe(t, s, "/mytopic/json", subscribeRR)
  462. publishRR := request(t, s, "PUT", "/mytopic", "my first message", nil)
  463. require.Equal(t, 200, publishRR.Code)
  464. subscribeCancel()
  465. messages := toMessages(t, subscribeRR.Body.String())
  466. require.Equal(t, 2, len(messages))
  467. require.Equal(t, openEvent, messages[0].Event)
  468. require.Equal(t, messageEvent, messages[1].Event)
  469. require.Equal(t, "my first message", messages[1].Message)
  470. response := request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  471. messages = toMessages(t, response.Body.String())
  472. require.Empty(t, messages)
  473. }
  474. func TestServer_PublishAndPollSince(t *testing.T) {
  475. t.Parallel()
  476. s := newTestServer(t, newTestConfig(t))
  477. request(t, s, "PUT", "/mytopic", "test 1", nil)
  478. time.Sleep(1100 * time.Millisecond)
  479. since := time.Now().Unix()
  480. request(t, s, "PUT", "/mytopic", "test 2", nil)
  481. response := request(t, s, "GET", fmt.Sprintf("/mytopic/json?poll=1&since=%d", since), "", nil)
  482. messages := toMessages(t, response.Body.String())
  483. require.Equal(t, 1, len(messages))
  484. require.Equal(t, "test 2", messages[0].Message)
  485. response = request(t, s, "GET", "/mytopic/json?poll=1&since=10s", "", nil)
  486. messages = toMessages(t, response.Body.String())
  487. require.Equal(t, 2, len(messages))
  488. require.Equal(t, "test 1", messages[0].Message)
  489. response = request(t, s, "GET", "/mytopic/json?poll=1&since=100ms", "", nil)
  490. messages = toMessages(t, response.Body.String())
  491. require.Equal(t, 1, len(messages))
  492. require.Equal(t, "test 2", messages[0].Message)
  493. response = request(t, s, "GET", "/mytopic/json?poll=1&since=latest", "", nil)
  494. messages = toMessages(t, response.Body.String())
  495. require.Equal(t, 1, len(messages))
  496. require.Equal(t, "test 2", messages[0].Message)
  497. response = request(t, s, "GET", "/mytopic/json?poll=1&since=INVALID", "", nil)
  498. require.Equal(t, 40008, toHTTPError(t, response.Body.String()).Code)
  499. }
  500. func newMessageWithTimestamp(topic, message string, timestamp int64) *message {
  501. m := newDefaultMessage(topic, message)
  502. m.Time = timestamp
  503. return m
  504. }
  505. func TestServer_PollSinceID_MultipleTopics(t *testing.T) {
  506. s := newTestServer(t, newTestConfig(t))
  507. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic1", "test 1", 1655740277)))
  508. markerMessage := newMessageWithTimestamp("mytopic2", "test 2", 1655740283)
  509. require.Nil(t, s.messageCache.AddMessage(markerMessage))
  510. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic1", "test 3", 1655740289)))
  511. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic2", "test 4", 1655740293)))
  512. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic1", "test 5", 1655740297)))
  513. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic2", "test 6", 1655740303)))
  514. response := request(t, s, "GET", fmt.Sprintf("/mytopic1,mytopic2/json?poll=1&since=%s", markerMessage.ID), "", nil)
  515. messages := toMessages(t, response.Body.String())
  516. require.Equal(t, 4, len(messages))
  517. require.Equal(t, "test 3", messages[0].Message)
  518. require.Equal(t, "mytopic1", messages[0].Topic)
  519. require.Equal(t, "test 4", messages[1].Message)
  520. require.Equal(t, "mytopic2", messages[1].Topic)
  521. require.Equal(t, "test 5", messages[2].Message)
  522. require.Equal(t, "mytopic1", messages[2].Topic)
  523. require.Equal(t, "test 6", messages[3].Message)
  524. require.Equal(t, "mytopic2", messages[3].Topic)
  525. }
  526. func TestServer_PollSinceID_MultipleTopics_IDDoesNotMatch(t *testing.T) {
  527. s := newTestServer(t, newTestConfig(t))
  528. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic1", "test 3", 1655740289)))
  529. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic2", "test 4", 1655740293)))
  530. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic1", "test 5", 1655740297)))
  531. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic2", "test 6", 1655740303)))
  532. response := request(t, s, "GET", "/mytopic1,mytopic2/json?poll=1&since=NoMatchForID", "", nil)
  533. messages := toMessages(t, response.Body.String())
  534. require.Equal(t, 4, len(messages))
  535. require.Equal(t, "test 3", messages[0].Message)
  536. require.Equal(t, "test 4", messages[1].Message)
  537. require.Equal(t, "test 5", messages[2].Message)
  538. require.Equal(t, "test 6", messages[3].Message)
  539. }
  540. func TestServer_PublishViaGET(t *testing.T) {
  541. s := newTestServer(t, newTestConfig(t))
  542. response := request(t, s, "GET", "/mytopic/trigger", "", nil)
  543. msg := toMessage(t, response.Body.String())
  544. require.NotEmpty(t, msg.ID)
  545. require.Equal(t, "triggered", msg.Message)
  546. 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)
  547. msg = toMessage(t, response.Body.String())
  548. require.NotEmpty(t, msg.ID)
  549. require.Equal(t, "This is a test", msg.Message)
  550. require.Equal(t, "This is a title", msg.Title)
  551. require.Equal(t, []string{"skull"}, msg.Tags)
  552. require.Equal(t, 5, msg.Priority)
  553. require.Greater(t, msg.Time, time.Now().Add(23*time.Hour).Unix())
  554. }
  555. func TestServer_PublishMessageInHeaderWithNewlines(t *testing.T) {
  556. s := newTestServer(t, newTestConfig(t))
  557. response := request(t, s, "PUT", "/mytopic", "", map[string]string{
  558. "Message": "Line 1\\nLine 2",
  559. })
  560. msg := toMessage(t, response.Body.String())
  561. require.NotEmpty(t, msg.ID)
  562. require.Equal(t, "Line 1\nLine 2", msg.Message) // \\n -> \n !
  563. }
  564. func TestServer_PublishInvalidTopic(t *testing.T) {
  565. s := newTestServer(t, newTestConfig(t))
  566. s.smtpSender = &testMailer{}
  567. response := request(t, s, "PUT", "/docs", "fail", nil)
  568. require.Equal(t, 40010, toHTTPError(t, response.Body.String()).Code)
  569. }
  570. func TestServer_PublishWithSIDInPath(t *testing.T) {
  571. s := newTestServer(t, newTestConfig(t))
  572. response := request(t, s, "POST", "/mytopic/sid", "message", nil)
  573. msg := toMessage(t, response.Body.String())
  574. require.NotEmpty(t, msg.ID)
  575. require.Equal(t, "sid", msg.SID)
  576. }
  577. func TestServer_PublishWithSIDInHeader(t *testing.T) {
  578. s := newTestServer(t, newTestConfig(t))
  579. response := request(t, s, "POST", "/mytopic", "message", map[string]string{
  580. "sid": "sid",
  581. })
  582. msg := toMessage(t, response.Body.String())
  583. require.NotEmpty(t, msg.ID)
  584. require.Equal(t, "sid", msg.SID)
  585. }
  586. func TestServer_PublishWithSIDInPathAndHeader(t *testing.T) {
  587. s := newTestServer(t, newTestConfig(t))
  588. response := request(t, s, "PUT", "/mytopic/sid1", "message", map[string]string{
  589. "sid": "sid2",
  590. })
  591. msg := toMessage(t, response.Body.String())
  592. require.NotEmpty(t, msg.ID)
  593. require.Equal(t, "sid1", msg.SID) // SID in path has priority over SID in header
  594. }
  595. func TestServer_PublishWithSIDInQuery(t *testing.T) {
  596. s := newTestServer(t, newTestConfig(t))
  597. response := request(t, s, "PUT", "/mytopic?sid=sid1", "message", nil)
  598. msg := toMessage(t, response.Body.String())
  599. require.NotEmpty(t, msg.ID)
  600. require.Equal(t, "sid1", msg.SID)
  601. }
  602. func TestServer_PublishWithSIDViaGet(t *testing.T) {
  603. s := newTestServer(t, newTestConfig(t))
  604. response := request(t, s, "GET", "/mytopic/publish?sid=sid1", "message", nil)
  605. msg := toMessage(t, response.Body.String())
  606. require.NotEmpty(t, msg.ID)
  607. require.Equal(t, "sid1", msg.SID)
  608. }
  609. func TestServer_PublishWithInvalidSIDInPath(t *testing.T) {
  610. s := newTestServer(t, newTestConfig(t))
  611. response := request(t, s, "POST", "/mytopic/.", "message", nil)
  612. require.Equal(t, 404, response.Code)
  613. }
  614. func TestServer_PublishWithInvalidSIDInHeader(t *testing.T) {
  615. s := newTestServer(t, newTestConfig(t))
  616. response := request(t, s, "POST", "/mytopic", "message", map[string]string{
  617. "X-Sequence-ID": "*&?",
  618. })
  619. require.Equal(t, 400, response.Code)
  620. require.Equal(t, 40049, toHTTPError(t, response.Body.String()).Code)
  621. }
  622. func TestServer_PollWithQueryFilters(t *testing.T) {
  623. s := newTestServer(t, newTestConfig(t))
  624. response := request(t, s, "PUT", "/mytopic?priority=1&tags=tag1,tag2", "my first message", nil)
  625. msg := toMessage(t, response.Body.String())
  626. require.NotEmpty(t, msg.ID)
  627. response = request(t, s, "PUT", "/mytopic?title=a+title", "my second message", map[string]string{
  628. "Tags": "tag2,tag3",
  629. })
  630. msg = toMessage(t, response.Body.String())
  631. require.NotEmpty(t, msg.ID)
  632. queriesThatShouldReturnMessageOne := []string{
  633. "/mytopic/json?poll=1&priority=1",
  634. "/mytopic/json?poll=1&priority=min",
  635. "/mytopic/json?poll=1&priority=min,low",
  636. "/mytopic/json?poll=1&priority=1,2",
  637. "/mytopic/json?poll=1&p=2,min",
  638. "/mytopic/json?poll=1&tags=tag1",
  639. "/mytopic/json?poll=1&tags=tag1,tag2",
  640. "/mytopic/json?poll=1&message=my+first+message",
  641. }
  642. for _, query := range queriesThatShouldReturnMessageOne {
  643. response = request(t, s, "GET", query, "", nil)
  644. messages := toMessages(t, response.Body.String())
  645. require.Equal(t, 1, len(messages), "Query failed: "+query)
  646. require.Equal(t, "my first message", messages[0].Message, "Query failed: "+query)
  647. }
  648. queriesThatShouldReturnMessageTwo := []string{
  649. "/mytopic/json?poll=1&x-priority=3", // !
  650. "/mytopic/json?poll=1&priority=3",
  651. "/mytopic/json?poll=1&priority=default",
  652. "/mytopic/json?poll=1&p=3",
  653. "/mytopic/json?poll=1&x-tags=tag2,tag3",
  654. "/mytopic/json?poll=1&tags=tag2,tag3",
  655. "/mytopic/json?poll=1&tag=tag2,tag3",
  656. "/mytopic/json?poll=1&ta=tag2,tag3",
  657. "/mytopic/json?poll=1&x-title=a+title",
  658. "/mytopic/json?poll=1&title=a+title",
  659. "/mytopic/json?poll=1&t=a+title",
  660. "/mytopic/json?poll=1&x-message=my+second+message",
  661. "/mytopic/json?poll=1&message=my+second+message",
  662. "/mytopic/json?poll=1&m=my+second+message",
  663. "/mytopic/json?x-poll=1&m=my+second+message",
  664. "/mytopic/json?po=1&m=my+second+message",
  665. }
  666. for _, query := range queriesThatShouldReturnMessageTwo {
  667. response = request(t, s, "GET", query, "", nil)
  668. messages := toMessages(t, response.Body.String())
  669. require.Equal(t, 1, len(messages), "Query failed: "+query)
  670. require.Equal(t, "my second message", messages[0].Message, "Query failed: "+query)
  671. }
  672. queriesThatShouldReturnNoMessages := []string{
  673. "/mytopic/json?poll=1&priority=4",
  674. "/mytopic/json?poll=1&tags=tag1,tag2,tag3",
  675. "/mytopic/json?poll=1&title=another+title",
  676. "/mytopic/json?poll=1&message=my+third+message",
  677. "/mytopic/json?poll=1&message=my+third+message",
  678. }
  679. for _, query := range queriesThatShouldReturnNoMessages {
  680. response = request(t, s, "GET", query, "", nil)
  681. messages := toMessages(t, response.Body.String())
  682. require.Equal(t, 0, len(messages), "Query failed: "+query)
  683. }
  684. }
  685. func TestServer_SubscribeWithQueryFilters(t *testing.T) {
  686. t.Parallel()
  687. c := newTestConfig(t)
  688. c.KeepaliveInterval = 800 * time.Millisecond
  689. s := newTestServer(t, c)
  690. subscribeResponse := httptest.NewRecorder()
  691. subscribeCancel := subscribe(t, s, "/mytopic/json?tags=zfs-issue", subscribeResponse)
  692. response := request(t, s, "PUT", "/mytopic", "my first message", nil)
  693. require.Equal(t, 200, response.Code)
  694. response = request(t, s, "PUT", "/mytopic", "ZFS scrub failed", map[string]string{
  695. "Tags": "zfs-issue,zfs-scrub",
  696. })
  697. require.Equal(t, 200, response.Code)
  698. time.Sleep(850 * time.Millisecond)
  699. subscribeCancel()
  700. messages := toMessages(t, subscribeResponse.Body.String())
  701. require.Equal(t, 3, len(messages))
  702. require.Equal(t, openEvent, messages[0].Event)
  703. require.Equal(t, messageEvent, messages[1].Event)
  704. require.Equal(t, "ZFS scrub failed", messages[1].Message)
  705. require.Equal(t, keepaliveEvent, messages[2].Event)
  706. }
  707. func TestServer_Auth_Success_Admin(t *testing.T) {
  708. c := newTestConfigWithAuthFile(t)
  709. s := newTestServer(t, c)
  710. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleAdmin, false))
  711. response := request(t, s, "GET", "/mytopic/auth", "", map[string]string{
  712. "Authorization": util.BasicAuth("phil", "phil"),
  713. })
  714. require.Equal(t, 200, response.Code)
  715. require.Equal(t, `{"success":true}`+"\n", response.Body.String())
  716. }
  717. func TestServer_Auth_Success_User(t *testing.T) {
  718. c := newTestConfigWithAuthFile(t)
  719. c.AuthDefault = user.PermissionDenyAll
  720. s := newTestServer(t, c)
  721. require.Nil(t, s.userManager.AddUser("ben", "ben", user.RoleUser, false))
  722. require.Nil(t, s.userManager.AllowAccess("ben", "mytopic", user.PermissionReadWrite))
  723. response := request(t, s, "GET", "/mytopic/auth", "", map[string]string{
  724. "Authorization": util.BasicAuth("ben", "ben"),
  725. })
  726. require.Equal(t, 200, response.Code)
  727. }
  728. func TestServer_Auth_Success_User_MultipleTopics(t *testing.T) {
  729. c := newTestConfigWithAuthFile(t)
  730. c.AuthDefault = user.PermissionDenyAll
  731. s := newTestServer(t, c)
  732. require.Nil(t, s.userManager.AddUser("ben", "ben", user.RoleUser, false))
  733. require.Nil(t, s.userManager.AllowAccess("ben", "mytopic", user.PermissionReadWrite))
  734. require.Nil(t, s.userManager.AllowAccess("ben", "anothertopic", user.PermissionReadWrite))
  735. response := request(t, s, "GET", "/mytopic,anothertopic/auth", "", map[string]string{
  736. "Authorization": util.BasicAuth("ben", "ben"),
  737. })
  738. require.Equal(t, 200, response.Code)
  739. response = request(t, s, "GET", "/mytopic,anothertopic,NOT-THIS-ONE/auth", "", map[string]string{
  740. "Authorization": util.BasicAuth("ben", "ben"),
  741. })
  742. require.Equal(t, 403, response.Code)
  743. }
  744. func TestServer_Auth_Fail_InvalidPass(t *testing.T) {
  745. c := newTestConfig(t)
  746. c.AuthFile = filepath.Join(t.TempDir(), "user.db")
  747. c.AuthDefault = user.PermissionDenyAll
  748. s := newTestServer(t, c)
  749. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleAdmin, false))
  750. response := request(t, s, "GET", "/mytopic/auth", "", map[string]string{
  751. "Authorization": util.BasicAuth("phil", "INVALID"),
  752. })
  753. require.Equal(t, 401, response.Code)
  754. }
  755. func TestServer_Auth_Fail_Unauthorized(t *testing.T) {
  756. c := newTestConfigWithAuthFile(t)
  757. c.AuthDefault = user.PermissionDenyAll
  758. s := newTestServer(t, c)
  759. require.Nil(t, s.userManager.AddUser("ben", "ben", user.RoleUser, false))
  760. require.Nil(t, s.userManager.AllowAccess("ben", "sometopic", user.PermissionReadWrite)) // Not mytopic!
  761. response := request(t, s, "GET", "/mytopic/auth", "", map[string]string{
  762. "Authorization": util.BasicAuth("ben", "ben"),
  763. })
  764. require.Equal(t, 403, response.Code)
  765. }
  766. func TestServer_Auth_Fail_CannotPublish(t *testing.T) {
  767. c := newTestConfigWithAuthFile(t)
  768. c.AuthDefault = user.PermissionReadWrite // Open by default
  769. s := newTestServer(t, c)
  770. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleAdmin, false))
  771. require.Nil(t, s.userManager.AllowAccess(user.Everyone, "private", user.PermissionDenyAll))
  772. require.Nil(t, s.userManager.AllowAccess(user.Everyone, "announcements", user.PermissionRead))
  773. response := request(t, s, "PUT", "/mytopic", "test", nil)
  774. require.Equal(t, 200, response.Code)
  775. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  776. require.Equal(t, 200, response.Code)
  777. response = request(t, s, "PUT", "/announcements", "test", nil)
  778. require.Equal(t, 403, response.Code) // Cannot write as anonymous
  779. response = request(t, s, "PUT", "/announcements", "test", map[string]string{
  780. "Authorization": util.BasicAuth("phil", "phil"),
  781. })
  782. require.Equal(t, 200, response.Code)
  783. response = request(t, s, "GET", "/announcements/json?poll=1", "", nil)
  784. require.Equal(t, 200, response.Code) // Anonymous read allowed
  785. response = request(t, s, "GET", "/private/json?poll=1", "", nil)
  786. require.Equal(t, 403, response.Code) // Anonymous read not allowed
  787. }
  788. func TestServer_Auth_Fail_Rate_Limiting(t *testing.T) {
  789. c := newTestConfigWithAuthFile(t)
  790. c.VisitorAuthFailureLimitBurst = 10
  791. s := newTestServer(t, c)
  792. for i := 0; i < 10; i++ {
  793. response := request(t, s, "PUT", "/announcements", "test", map[string]string{
  794. "Authorization": util.BasicAuth("phil", "phil"),
  795. })
  796. require.Equal(t, 401, response.Code)
  797. }
  798. response := request(t, s, "PUT", "/announcements", "test", map[string]string{
  799. "Authorization": util.BasicAuth("phil", "phil"),
  800. })
  801. require.Equal(t, 429, response.Code)
  802. require.Equal(t, 42909, toHTTPError(t, response.Body.String()).Code)
  803. }
  804. func TestServer_Auth_ViaQuery(t *testing.T) {
  805. c := newTestConfigWithAuthFile(t)
  806. c.AuthDefault = user.PermissionDenyAll
  807. s := newTestServer(t, c)
  808. require.Nil(t, s.userManager.AddUser("ben", "some pass", user.RoleAdmin, false))
  809. u := fmt.Sprintf("/mytopic/json?poll=1&auth=%s", base64.RawURLEncoding.EncodeToString([]byte(util.BasicAuth("ben", "some pass"))))
  810. response := request(t, s, "GET", u, "", nil)
  811. require.Equal(t, 200, response.Code)
  812. u = fmt.Sprintf("/mytopic/json?poll=1&auth=%s", base64.RawURLEncoding.EncodeToString([]byte(util.BasicAuth("ben", "WRONNNGGGG"))))
  813. response = request(t, s, "GET", u, "", nil)
  814. require.Equal(t, 401, response.Code)
  815. }
  816. func TestServer_Auth_NonBasicHeader(t *testing.T) {
  817. s := newTestServer(t, newTestConfigWithAuthFile(t))
  818. response := request(t, s, "PUT", "/mytopic", "test", map[string]string{
  819. "Authorization": "WebPush not-supported",
  820. })
  821. require.Equal(t, 200, response.Code)
  822. response = request(t, s, "PUT", "/mytopic", "test", map[string]string{
  823. "Authorization": "Bearer supported",
  824. })
  825. require.Equal(t, 401, response.Code)
  826. response = request(t, s, "PUT", "/mytopic", "test", map[string]string{
  827. "Authorization": "basic supported",
  828. })
  829. require.Equal(t, 401, response.Code)
  830. }
  831. func TestServer_StatsResetter(t *testing.T) {
  832. t.Parallel()
  833. // This tests the stats resetter for
  834. // - an anonymous user
  835. // - a user without a tier (treated like the same as the anonymous user)
  836. // - a user with a tier
  837. c := newTestConfigWithAuthFile(t)
  838. c.VisitorStatsResetTime = time.Now().Add(2 * time.Second)
  839. s := newTestServer(t, c)
  840. go s.runStatsResetter()
  841. // Create user with tier (tieruser) and user without tier (phil)
  842. require.Nil(t, s.userManager.AddTier(&user.Tier{
  843. Code: "test",
  844. MessageLimit: 5,
  845. MessageExpiryDuration: -5 * time.Second, // Second, what a hack!
  846. }))
  847. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser, false))
  848. require.Nil(t, s.userManager.AddUser("tieruser", "tieruser", user.RoleUser, false))
  849. require.Nil(t, s.userManager.ChangeTier("tieruser", "test"))
  850. // Send an anonymous message
  851. response := request(t, s, "PUT", "/mytopic", "test", nil)
  852. require.Equal(t, 200, response.Code)
  853. // Send messages from user without tier (phil)
  854. for i := 0; i < 5; i++ {
  855. response := request(t, s, "PUT", "/mytopic", "test", map[string]string{
  856. "Authorization": util.BasicAuth("phil", "phil"),
  857. })
  858. require.Equal(t, 200, response.Code)
  859. }
  860. // Send messages from user with tier
  861. for i := 0; i < 2; i++ {
  862. response := request(t, s, "PUT", "/mytopic", "test", map[string]string{
  863. "Authorization": util.BasicAuth("tieruser", "tieruser"),
  864. })
  865. require.Equal(t, 200, response.Code)
  866. }
  867. // User stats show 6 messages (for user without tier)
  868. response = request(t, s, "GET", "/v1/account", "", map[string]string{
  869. "Authorization": util.BasicAuth("phil", "phil"),
  870. })
  871. require.Equal(t, 200, response.Code)
  872. account, err := util.UnmarshalJSON[apiAccountResponse](io.NopCloser(response.Body))
  873. require.Nil(t, err)
  874. require.Equal(t, int64(6), account.Stats.Messages)
  875. // User stats show 6 messages (for anonymous visitor)
  876. response = request(t, s, "GET", "/v1/account", "", nil)
  877. require.Equal(t, 200, response.Code)
  878. account, err = util.UnmarshalJSON[apiAccountResponse](io.NopCloser(response.Body))
  879. require.Nil(t, err)
  880. require.Equal(t, int64(6), account.Stats.Messages)
  881. // User stats show 2 messages (for user with tier)
  882. response = request(t, s, "GET", "/v1/account", "", map[string]string{
  883. "Authorization": util.BasicAuth("tieruser", "tieruser"),
  884. })
  885. require.Equal(t, 200, response.Code)
  886. account, err = util.UnmarshalJSON[apiAccountResponse](io.NopCloser(response.Body))
  887. require.Nil(t, err)
  888. require.Equal(t, int64(2), account.Stats.Messages)
  889. // Wait for stats resetter to run
  890. waitFor(t, func() bool {
  891. response = request(t, s, "GET", "/v1/account", "", map[string]string{
  892. "Authorization": util.BasicAuth("phil", "phil"),
  893. })
  894. require.Equal(t, 200, response.Code)
  895. account, err = util.UnmarshalJSON[apiAccountResponse](io.NopCloser(response.Body))
  896. require.Nil(t, err)
  897. return account.Stats.Messages == 0
  898. })
  899. // User stats show 0 messages now!
  900. response = request(t, s, "GET", "/v1/account", "", map[string]string{
  901. "Authorization": util.BasicAuth("phil", "phil"),
  902. })
  903. require.Equal(t, 200, response.Code)
  904. account, err = util.UnmarshalJSON[apiAccountResponse](io.NopCloser(response.Body))
  905. require.Nil(t, err)
  906. require.Equal(t, int64(0), account.Stats.Messages)
  907. // Since this is a user without a tier, the anonymous user should have the same stats
  908. response = request(t, s, "GET", "/v1/account", "", nil)
  909. require.Equal(t, 200, response.Code)
  910. account, err = util.UnmarshalJSON[apiAccountResponse](io.NopCloser(response.Body))
  911. require.Nil(t, err)
  912. require.Equal(t, int64(0), account.Stats.Messages)
  913. // User stats show 0 messages (for user with tier)
  914. response = request(t, s, "GET", "/v1/account", "", map[string]string{
  915. "Authorization": util.BasicAuth("tieruser", "tieruser"),
  916. })
  917. require.Equal(t, 200, response.Code)
  918. account, err = util.UnmarshalJSON[apiAccountResponse](io.NopCloser(response.Body))
  919. require.Nil(t, err)
  920. require.Equal(t, int64(0), account.Stats.Messages)
  921. }
  922. func TestServer_StatsResetter_MessageLimiter_EmailsLimiter(t *testing.T) {
  923. // This tests that the messageLimiter (the only fixed limiter) and the emailsLimiter (token bucket)
  924. // is reset by the stats resetter
  925. c := newTestConfigWithAuthFile(t)
  926. s := newTestServer(t, c)
  927. s.smtpSender = &testMailer{}
  928. // Publish some messages, and check stats
  929. for i := 0; i < 3; i++ {
  930. response := request(t, s, "PUT", "/mytopic", "test", nil)
  931. require.Equal(t, 200, response.Code)
  932. }
  933. response := request(t, s, "PUT", "/mytopic", "test", map[string]string{
  934. "Email": "test@email.com",
  935. })
  936. require.Equal(t, 200, response.Code)
  937. rr := request(t, s, "GET", "/v1/account", "", nil)
  938. require.Equal(t, 200, rr.Code)
  939. account, err := util.UnmarshalJSON[apiAccountResponse](io.NopCloser(rr.Body))
  940. require.Nil(t, err)
  941. require.Equal(t, int64(4), account.Stats.Messages)
  942. require.Equal(t, int64(1), account.Stats.Emails)
  943. v := s.visitor(netip.MustParseAddr("9.9.9.9"), nil)
  944. require.Equal(t, int64(4), v.Stats().Messages)
  945. require.Equal(t, int64(4), v.messagesLimiter.Value())
  946. require.Equal(t, int64(1), v.Stats().Emails)
  947. require.Equal(t, int64(1), v.emailsLimiter.Value())
  948. // Reset stats and check again
  949. s.resetStats()
  950. rr = request(t, s, "GET", "/v1/account", "", nil)
  951. require.Equal(t, 200, rr.Code)
  952. account, err = util.UnmarshalJSON[apiAccountResponse](io.NopCloser(rr.Body))
  953. require.Nil(t, err)
  954. require.Equal(t, int64(0), account.Stats.Messages)
  955. require.Equal(t, int64(0), account.Stats.Emails)
  956. v = s.visitor(netip.MustParseAddr("9.9.9.9"), nil)
  957. require.Equal(t, int64(0), v.Stats().Messages)
  958. require.Equal(t, int64(0), v.messagesLimiter.Value())
  959. require.Equal(t, int64(0), v.Stats().Emails)
  960. require.Equal(t, int64(0), v.emailsLimiter.Value())
  961. }
  962. func TestServer_DailyMessageQuotaFromDatabase(t *testing.T) {
  963. t.Parallel()
  964. // This tests that the daily message quota is prefilled originally from the database,
  965. // if the visitor is unknown
  966. c := newTestConfigWithAuthFile(t)
  967. c.AuthStatsQueueWriterInterval = 100 * time.Millisecond
  968. s := newTestServer(t, c)
  969. // Create user, and update it with some message and email stats
  970. require.Nil(t, s.userManager.AddTier(&user.Tier{
  971. Code: "test",
  972. }))
  973. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser, false))
  974. require.Nil(t, s.userManager.ChangeTier("phil", "test"))
  975. u, err := s.userManager.User("phil")
  976. require.Nil(t, err)
  977. s.userManager.EnqueueUserStats(u.ID, &user.Stats{
  978. Messages: 123456,
  979. Emails: 999,
  980. })
  981. time.Sleep(400 * time.Millisecond)
  982. // Get account and verify stats are read from the DB, and that the visitor also has these stats
  983. rr := request(t, s, "GET", "/v1/account", "", map[string]string{
  984. "Authorization": util.BasicAuth("phil", "phil"),
  985. })
  986. require.Equal(t, 200, rr.Code)
  987. account, err := util.UnmarshalJSON[apiAccountResponse](io.NopCloser(rr.Body))
  988. require.Nil(t, err)
  989. require.Equal(t, int64(123456), account.Stats.Messages)
  990. require.Equal(t, int64(999), account.Stats.Emails)
  991. v := s.visitor(netip.MustParseAddr("9.9.9.9"), u)
  992. require.Equal(t, int64(123456), v.Stats().Messages)
  993. require.Equal(t, int64(123456), v.messagesLimiter.Value())
  994. require.Equal(t, int64(999), v.Stats().Emails)
  995. require.Equal(t, int64(999), v.emailsLimiter.Value())
  996. }
  997. type testMailer struct {
  998. count int
  999. mu sync.Mutex
  1000. }
  1001. func (t *testMailer) Send(v *visitor, m *message, to string) error {
  1002. t.mu.Lock()
  1003. defer t.mu.Unlock()
  1004. t.count++
  1005. return nil
  1006. }
  1007. func (t *testMailer) Counts() (total int64, success int64, failure int64) {
  1008. return 0, 0, 0
  1009. }
  1010. func (t *testMailer) Count() int {
  1011. t.mu.Lock()
  1012. defer t.mu.Unlock()
  1013. return t.count
  1014. }
  1015. func TestServer_PublishTooManyRequests_Defaults(t *testing.T) {
  1016. s := newTestServer(t, newTestConfig(t))
  1017. for i := 0; i < 60; i++ {
  1018. response := request(t, s, "PUT", "/mytopic", fmt.Sprintf("message %d", i), nil)
  1019. require.Equal(t, 200, response.Code)
  1020. }
  1021. response := request(t, s, "PUT", "/mytopic", "message", nil)
  1022. require.Equal(t, 429, response.Code)
  1023. }
  1024. func TestServer_PublishTooManyRequests_Defaults_IPv6(t *testing.T) {
  1025. s := newTestServer(t, newTestConfig(t))
  1026. overrideRemoteAddr1 := func(r *http.Request) {
  1027. r.RemoteAddr = "[2001:db8:9999:8888:1::1]:1234"
  1028. }
  1029. overrideRemoteAddr2 := func(r *http.Request) {
  1030. r.RemoteAddr = "[2001:db8:9999:8888:2::1]:1234" // Same /64
  1031. }
  1032. for i := 0; i < 30; i++ {
  1033. response := request(t, s, "PUT", "/mytopic", fmt.Sprintf("message %d", i), nil, overrideRemoteAddr1)
  1034. require.Equal(t, 200, response.Code)
  1035. }
  1036. for i := 0; i < 30; i++ {
  1037. response := request(t, s, "PUT", "/mytopic", fmt.Sprintf("message %d", i), nil, overrideRemoteAddr2)
  1038. require.Equal(t, 200, response.Code)
  1039. }
  1040. response := request(t, s, "PUT", "/mytopic", "message", nil, overrideRemoteAddr1)
  1041. require.Equal(t, 429, response.Code)
  1042. }
  1043. func TestServer_PublishTooManyRequests_IPv6_Slash48(t *testing.T) {
  1044. c := newTestConfig(t)
  1045. c.VisitorRequestLimitBurst = 6
  1046. c.VisitorPrefixBitsIPv6 = 48 // Use /48 for IPv6 prefixes
  1047. s := newTestServer(t, c)
  1048. overrideRemoteAddr1 := func(r *http.Request) {
  1049. r.RemoteAddr = "[2001:db8:9999::1]:1234"
  1050. }
  1051. overrideRemoteAddr2 := func(r *http.Request) {
  1052. r.RemoteAddr = "[2001:db8:9999::2]:1234" // Same /48
  1053. }
  1054. for i := 0; i < 3; i++ {
  1055. response := request(t, s, "PUT", "/mytopic", fmt.Sprintf("message %d", i), nil, overrideRemoteAddr1)
  1056. require.Equal(t, 200, response.Code)
  1057. }
  1058. for i := 0; i < 3; i++ {
  1059. response := request(t, s, "PUT", "/mytopic", fmt.Sprintf("message %d", i), nil, overrideRemoteAddr2)
  1060. require.Equal(t, 200, response.Code)
  1061. }
  1062. response := request(t, s, "PUT", "/mytopic", "message", nil, overrideRemoteAddr1)
  1063. require.Equal(t, 429, response.Code)
  1064. }
  1065. func TestServer_PublishTooManyRequests_Defaults_ExemptHosts(t *testing.T) {
  1066. c := newTestConfig(t)
  1067. c.VisitorRequestLimitBurst = 3
  1068. c.VisitorRequestExemptPrefixes = []netip.Prefix{netip.MustParsePrefix("9.9.9.9/32")} // see request()
  1069. s := newTestServer(t, c)
  1070. for i := 0; i < 5; i++ { // > 3
  1071. response := request(t, s, "PUT", "/mytopic", fmt.Sprintf("message %d", i), nil)
  1072. require.Equal(t, 200, response.Code)
  1073. }
  1074. }
  1075. func TestServer_PublishTooManyRequests_Defaults_ExemptHosts_IPv6(t *testing.T) {
  1076. c := newTestConfig(t)
  1077. c.VisitorRequestLimitBurst = 3
  1078. c.VisitorRequestExemptPrefixes = []netip.Prefix{netip.MustParsePrefix("2001:db8:9999::/48")}
  1079. s := newTestServer(t, c)
  1080. overrideRemoteAddr := func(r *http.Request) {
  1081. r.RemoteAddr = "[2001:db8:9999::1]:1234"
  1082. }
  1083. for i := 0; i < 5; i++ { // > 3
  1084. response := request(t, s, "PUT", "/mytopic", fmt.Sprintf("message %d", i), nil, overrideRemoteAddr)
  1085. require.Equal(t, 200, response.Code)
  1086. }
  1087. }
  1088. func TestServer_PublishTooManyRequests_Defaults_ExemptHosts_MessageDailyLimit(t *testing.T) {
  1089. c := newTestConfig(t)
  1090. c.VisitorRequestLimitBurst = 10
  1091. c.VisitorMessageDailyLimit = 4
  1092. c.VisitorRequestExemptPrefixes = []netip.Prefix{netip.MustParsePrefix("9.9.9.9/32")} // see request()
  1093. s := newTestServer(t, c)
  1094. for i := 0; i < 8; i++ { // 4
  1095. response := request(t, s, "PUT", "/mytopic", "message", nil)
  1096. require.Equal(t, 200, response.Code)
  1097. }
  1098. }
  1099. func TestServer_PublishTooManyRequests_ShortReplenish(t *testing.T) {
  1100. t.Parallel()
  1101. c := newTestConfig(t)
  1102. c.VisitorRequestLimitBurst = 60
  1103. c.VisitorRequestLimitReplenish = time.Second
  1104. s := newTestServer(t, c)
  1105. for i := 0; i < 60; i++ {
  1106. response := request(t, s, "PUT", "/mytopic", fmt.Sprintf("message %d", i), nil)
  1107. require.Equal(t, 200, response.Code)
  1108. }
  1109. response := request(t, s, "PUT", "/mytopic", "message", nil)
  1110. require.Equal(t, 429, response.Code)
  1111. time.Sleep(1020 * time.Millisecond)
  1112. response = request(t, s, "PUT", "/mytopic", "message", nil)
  1113. require.Equal(t, 200, response.Code)
  1114. }
  1115. func TestServer_PublishTooManyEmails_Defaults(t *testing.T) {
  1116. s := newTestServer(t, newTestConfig(t))
  1117. s.smtpSender = &testMailer{}
  1118. for i := 0; i < 16; i++ {
  1119. response := request(t, s, "PUT", "/mytopic", fmt.Sprintf("message %d", i), map[string]string{
  1120. "E-Mail": "test@example.com",
  1121. })
  1122. require.Equal(t, 200, response.Code)
  1123. }
  1124. response := request(t, s, "PUT", "/mytopic", "one too many", map[string]string{
  1125. "E-Mail": "test@example.com",
  1126. })
  1127. require.Equal(t, 429, response.Code)
  1128. }
  1129. func TestServer_PublishTooManyEmails_Replenish(t *testing.T) {
  1130. t.Parallel()
  1131. c := newTestConfig(t)
  1132. c.VisitorEmailLimitReplenish = 500 * time.Millisecond
  1133. s := newTestServer(t, c)
  1134. s.smtpSender = &testMailer{}
  1135. for i := 0; i < 16; i++ {
  1136. response := request(t, s, "PUT", "/mytopic", fmt.Sprintf("message %d", i), map[string]string{
  1137. "E-Mail": "test@example.com",
  1138. })
  1139. require.Equal(t, 200, response.Code)
  1140. }
  1141. response := request(t, s, "PUT", "/mytopic", "one too many", map[string]string{
  1142. "E-Mail": "test@example.com",
  1143. })
  1144. require.Equal(t, 429, response.Code)
  1145. time.Sleep(510 * time.Millisecond)
  1146. response = request(t, s, "PUT", "/mytopic", "this should be okay again too many", map[string]string{
  1147. "E-Mail": "test@example.com",
  1148. })
  1149. require.Equal(t, 200, response.Code)
  1150. response = request(t, s, "PUT", "/mytopic", "and bad again", map[string]string{
  1151. "E-Mail": "test@example.com",
  1152. })
  1153. require.Equal(t, 429, response.Code)
  1154. }
  1155. func TestServer_PublishDelayedEmail_Fail(t *testing.T) {
  1156. s := newTestServer(t, newTestConfig(t))
  1157. s.smtpSender = &testMailer{}
  1158. response := request(t, s, "PUT", "/mytopic", "fail", map[string]string{
  1159. "E-Mail": "test@example.com",
  1160. "Delay": "20 min",
  1161. })
  1162. require.Equal(t, 40003, toHTTPError(t, response.Body.String()).Code)
  1163. }
  1164. func TestServer_PublishDelayedCall_Fail(t *testing.T) {
  1165. c := newTestConfigWithAuthFile(t)
  1166. c.TwilioAccount = "AC1234567890"
  1167. c.TwilioAuthToken = "AAEAA1234567890"
  1168. c.TwilioPhoneNumber = "+1234567890"
  1169. s := newTestServer(t, c)
  1170. response := request(t, s, "PUT", "/mytopic", "fail", map[string]string{
  1171. "Call": "yes",
  1172. "Delay": "20 min",
  1173. })
  1174. require.Equal(t, 40037, toHTTPError(t, response.Body.String()).Code)
  1175. }
  1176. func TestServer_PublishEmailNoMailer_Fail(t *testing.T) {
  1177. s := newTestServer(t, newTestConfig(t))
  1178. response := request(t, s, "PUT", "/mytopic", "fail", map[string]string{
  1179. "E-Mail": "test@example.com",
  1180. })
  1181. require.Equal(t, 400, response.Code)
  1182. }
  1183. func TestServer_PublishAndExpungeTopicAfter16Hours(t *testing.T) {
  1184. t.Parallel()
  1185. s := newTestServer(t, newTestConfig(t))
  1186. defer s.messageCache.Close()
  1187. subFn := func(v *visitor, msg *message) error {
  1188. return nil
  1189. }
  1190. // Publish and check last access
  1191. response := request(t, s, "POST", "/mytopic", "test", map[string]string{
  1192. "Cache": "no",
  1193. })
  1194. require.Equal(t, 200, response.Code)
  1195. waitFor(t, func() bool {
  1196. s.mu.Lock()
  1197. tp, exists := s.topics["mytopic"]
  1198. s.mu.Unlock()
  1199. if !exists {
  1200. return false
  1201. }
  1202. // .lastAccess set in t.Publish() -> t.Keepalive() in Goroutine
  1203. tp.mu.RLock()
  1204. defer tp.mu.RUnlock()
  1205. return tp.lastAccess.Unix() >= time.Now().Unix()-2 &&
  1206. tp.lastAccess.Unix() <= time.Now().Unix()+2
  1207. })
  1208. // Hack!
  1209. time.Sleep(time.Second)
  1210. // Topic won't get pruned
  1211. s.execManager()
  1212. require.NotNil(t, s.topics["mytopic"])
  1213. // Fudge with last access, but subscribe, and see that it won't get pruned (because of subscriber)
  1214. subID := s.topics["mytopic"].Subscribe(subFn, "", func() {})
  1215. s.topics["mytopic"].mu.Lock()
  1216. s.topics["mytopic"].lastAccess = time.Now().Add(-17 * time.Hour)
  1217. s.topics["mytopic"].mu.Unlock()
  1218. s.execManager()
  1219. require.NotNil(t, s.topics["mytopic"])
  1220. // It'll finally get pruned now that there are no subscribers and last access is 17 hours ago
  1221. s.topics["mytopic"].Unsubscribe(subID)
  1222. s.execManager()
  1223. require.Nil(t, s.topics["mytopic"])
  1224. }
  1225. func TestServer_TopicKeepaliveOnPoll(t *testing.T) {
  1226. t.Parallel()
  1227. s := newTestServer(t, newTestConfig(t))
  1228. // Create topic by polling once
  1229. response := request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  1230. require.Equal(t, 200, response.Code)
  1231. // Mess with last access time
  1232. s.topics["mytopic"].lastAccess = time.Now().Add(-17 * time.Hour)
  1233. // Poll again and check keepalive time
  1234. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  1235. require.Equal(t, 200, response.Code)
  1236. require.True(t, s.topics["mytopic"].lastAccess.Unix() >= time.Now().Unix()-2)
  1237. require.True(t, s.topics["mytopic"].lastAccess.Unix() <= time.Now().Unix()+2)
  1238. }
  1239. func TestServer_UnifiedPushDiscovery(t *testing.T) {
  1240. s := newTestServer(t, newTestConfig(t))
  1241. response := request(t, s, "GET", "/mytopic?up=1", "", nil)
  1242. require.Equal(t, 200, response.Code)
  1243. require.Equal(t, `{"unifiedpush":{"version":1}}`+"\n", response.Body.String())
  1244. }
  1245. func TestServer_PublishUnifiedPushBinary_AndPoll(t *testing.T) {
  1246. b := make([]byte, 12) // Max length
  1247. _, err := rand.Read(b)
  1248. require.Nil(t, err)
  1249. s := newTestServer(t, newTestConfig(t))
  1250. // Register a UnifiedPush subscriber
  1251. response := request(t, s, "GET", "/up123456789012/json?poll=1", "", nil)
  1252. require.Equal(t, 200, response.Code)
  1253. // Publish message to topic
  1254. response = request(t, s, "PUT", "/up123456789012?up=1", string(b), nil)
  1255. require.Equal(t, 200, response.Code)
  1256. m := toMessage(t, response.Body.String())
  1257. require.Equal(t, "base64", m.Encoding)
  1258. b2, err := base64.StdEncoding.DecodeString(m.Message)
  1259. require.Nil(t, err)
  1260. require.Equal(t, b, b2)
  1261. // Retrieve and check published message
  1262. response = request(t, s, "GET", "/up123456789012/json?poll=1", string(b), nil)
  1263. require.Equal(t, 200, response.Code)
  1264. m = toMessage(t, response.Body.String())
  1265. require.Equal(t, "base64", m.Encoding)
  1266. b2, err = base64.StdEncoding.DecodeString(m.Message)
  1267. require.Nil(t, err)
  1268. require.Equal(t, b, b2)
  1269. }
  1270. func TestServer_PublishUnifiedPushBinary_Truncated(t *testing.T) {
  1271. b := make([]byte, 5000) // Longer than max length
  1272. _, err := rand.Read(b)
  1273. require.Nil(t, err)
  1274. s := newTestServer(t, newTestConfig(t))
  1275. // Register a UnifiedPush subscriber
  1276. response := request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  1277. require.Equal(t, 200, response.Code)
  1278. // Publish message to topic
  1279. response = request(t, s, "PUT", "/mytopic?up=1", string(b), nil)
  1280. require.Equal(t, 200, response.Code)
  1281. m := toMessage(t, response.Body.String())
  1282. require.Equal(t, "base64", m.Encoding)
  1283. b2, err := base64.StdEncoding.DecodeString(m.Message)
  1284. require.Nil(t, err)
  1285. require.Equal(t, 4096, len(b2))
  1286. require.Equal(t, b[:4096], b2)
  1287. }
  1288. func TestServer_PublishUnifiedPushText(t *testing.T) {
  1289. s := newTestServer(t, newTestConfig(t))
  1290. // Register a UnifiedPush subscriber
  1291. response := request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  1292. require.Equal(t, 200, response.Code)
  1293. // Publish UnifiedPush text message
  1294. response = request(t, s, "PUT", "/mytopic?up=1", "this is a unifiedpush text message", nil)
  1295. require.Equal(t, 200, response.Code)
  1296. m := toMessage(t, response.Body.String())
  1297. require.Equal(t, "", m.Encoding)
  1298. require.Equal(t, "this is a unifiedpush text message", m.Message)
  1299. }
  1300. func TestServer_MatrixGateway_Discovery_Success(t *testing.T) {
  1301. s := newTestServer(t, newTestConfig(t))
  1302. response := request(t, s, "GET", "/_matrix/push/v1/notify", "", nil)
  1303. require.Equal(t, 200, response.Code)
  1304. require.Equal(t, `{"unifiedpush":{"gateway":"matrix"}}`+"\n", response.Body.String())
  1305. }
  1306. func TestServer_MatrixGateway_Discovery_Failure_Unconfigured(t *testing.T) {
  1307. c := newTestConfig(t)
  1308. c.BaseURL = ""
  1309. s := newTestServer(t, c)
  1310. response := request(t, s, "GET", "/_matrix/push/v1/notify", "", nil)
  1311. require.Equal(t, 500, response.Code)
  1312. err := toHTTPError(t, response.Body.String())
  1313. require.Equal(t, 50003, err.Code)
  1314. }
  1315. func TestServer_MatrixGateway_Push_Success(t *testing.T) {
  1316. s := newTestServer(t, newTestConfig(t))
  1317. response := request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  1318. require.Equal(t, 200, response.Code)
  1319. notification := `{"notification":{"devices":[{"pushkey":"http://127.0.0.1:12345/mytopic?up=1"}]}}`
  1320. response = request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1321. require.Equal(t, 200, response.Code)
  1322. require.Equal(t, `{"rejected":[]}`+"\n", response.Body.String())
  1323. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  1324. require.Equal(t, 200, response.Code)
  1325. m := toMessage(t, response.Body.String())
  1326. require.Equal(t, notification, m.Message)
  1327. }
  1328. func TestServer_MatrixGateway_Push_Failure_NoSubscriber(t *testing.T) {
  1329. c := newTestConfig(t)
  1330. c.VisitorSubscriberRateLimiting = true
  1331. s := newTestServer(t, c)
  1332. notification := `{"notification":{"devices":[{"pushkey":"http://127.0.0.1:12345/mytopic?up=1"}]}}`
  1333. response := request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1334. require.Equal(t, 507, response.Code)
  1335. require.Equal(t, 50701, toHTTPError(t, response.Body.String()).Code)
  1336. }
  1337. func TestServer_MatrixGateway_Push_Failure_NoSubscriber_After13Hours(t *testing.T) {
  1338. c := newTestConfig(t)
  1339. c.VisitorSubscriberRateLimiting = true
  1340. s := newTestServer(t, c)
  1341. notification := `{"notification":{"devices":[{"pushkey":"http://127.0.0.1:12345/mytopic?up=1"}]}}`
  1342. // No success if no rate visitor set (this also creates the topic in memory)
  1343. response := request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1344. require.Equal(t, 507, response.Code)
  1345. require.Equal(t, 50701, toHTTPError(t, response.Body.String()).Code)
  1346. require.Nil(t, s.topics["mytopic"].rateVisitor)
  1347. // Fake: This topic has been around for 13 hours without a rate visitor
  1348. s.topics["mytopic"].lastAccess = time.Now().Add(-13 * time.Hour)
  1349. // Same request should now return HTTP 200 with a rejected pushkey
  1350. response = request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1351. require.Equal(t, 200, response.Code)
  1352. require.Equal(t, `{"rejected":["http://127.0.0.1:12345/mytopic?up=1"]}`, strings.TrimSpace(response.Body.String()))
  1353. // Slightly unrelated: Test that topic is pruned after 16 hours
  1354. s.topics["mytopic"].lastAccess = time.Now().Add(-17 * time.Hour)
  1355. s.execManager()
  1356. require.Nil(t, s.topics["mytopic"])
  1357. }
  1358. func TestServer_MatrixGateway_Push_Failure_InvalidPushkey(t *testing.T) {
  1359. s := newTestServer(t, newTestConfig(t))
  1360. notification := `{"notification":{"devices":[{"pushkey":"http://wrong-base-url.com/mytopic?up=1"}]}}`
  1361. response := request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1362. require.Equal(t, 200, response.Code)
  1363. require.Equal(t, `{"rejected":["http://wrong-base-url.com/mytopic?up=1"]}`+"\n", response.Body.String())
  1364. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  1365. require.Equal(t, 200, response.Code)
  1366. require.Equal(t, "", response.Body.String()) // Empty!
  1367. }
  1368. func TestServer_MatrixGateway_Push_Failure_EverythingIsWrong(t *testing.T) {
  1369. s := newTestServer(t, newTestConfig(t))
  1370. notification := `{"message":"this is not really a Matrix message"}`
  1371. response := request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1372. require.Equal(t, 400, response.Code)
  1373. require.Equal(t, 40019, toHTTPError(t, response.Body.String()).Code)
  1374. notification = `this isn't even JSON'`
  1375. response = request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1376. require.Equal(t, 400, response.Code)
  1377. require.Equal(t, 40019, toHTTPError(t, response.Body.String()).Code)
  1378. }
  1379. func TestServer_MatrixGateway_Push_Failure_Unconfigured(t *testing.T) {
  1380. c := newTestConfig(t)
  1381. c.BaseURL = ""
  1382. s := newTestServer(t, c)
  1383. notification := `{"notification":{"devices":[{"pushkey":"http://127.0.0.1:12345/mytopic?up=1"}]}}`
  1384. response := request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1385. require.Equal(t, 500, response.Code)
  1386. require.Equal(t, 50003, toHTTPError(t, response.Body.String()).Code)
  1387. }
  1388. func TestServer_PublishActions_AndPoll(t *testing.T) {
  1389. s := newTestServer(t, newTestConfig(t))
  1390. response := request(t, s, "PUT", "/mytopic", "my message", map[string]string{
  1391. "Actions": "view, Open portal, https://home.nest.com/; http, Turn down, https://api.nest.com/device/XZ1D2, body=target_temp_f=65",
  1392. })
  1393. require.Equal(t, 200, response.Code)
  1394. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  1395. require.Equal(t, 200, response.Code)
  1396. m := toMessage(t, response.Body.String())
  1397. require.Equal(t, 2, len(m.Actions))
  1398. require.Equal(t, "view", m.Actions[0].Action)
  1399. require.Equal(t, "Open portal", m.Actions[0].Label)
  1400. require.Equal(t, "https://home.nest.com/", m.Actions[0].URL)
  1401. require.Equal(t, "http", m.Actions[1].Action)
  1402. require.Equal(t, "Turn down", m.Actions[1].Label)
  1403. require.Equal(t, "https://api.nest.com/device/XZ1D2", m.Actions[1].URL)
  1404. require.Equal(t, "target_temp_f=65", m.Actions[1].Body)
  1405. }
  1406. func TestServer_PublishMarkdown(t *testing.T) {
  1407. s := newTestServer(t, newTestConfig(t))
  1408. response := request(t, s, "PUT", "/mytopic", "**make this bold**", map[string]string{
  1409. "Content-Type": "text/markdown",
  1410. })
  1411. require.Equal(t, 200, response.Code)
  1412. m := toMessage(t, response.Body.String())
  1413. require.Equal(t, "**make this bold**", m.Message)
  1414. require.Equal(t, "text/markdown", m.ContentType)
  1415. }
  1416. func TestServer_PublishMarkdown_QueryParam(t *testing.T) {
  1417. s := newTestServer(t, newTestConfig(t))
  1418. response := request(t, s, "PUT", "/mytopic?md=1", "**make this bold**", nil)
  1419. require.Equal(t, 200, response.Code)
  1420. m := toMessage(t, response.Body.String())
  1421. require.Equal(t, "**make this bold**", m.Message)
  1422. require.Equal(t, "text/markdown", m.ContentType)
  1423. }
  1424. func TestServer_PublishMarkdown_NotMarkdown(t *testing.T) {
  1425. s := newTestServer(t, newTestConfig(t))
  1426. response := request(t, s, "PUT", "/mytopic", "**make this bold**", map[string]string{
  1427. "Content-Type": "not-markdown",
  1428. })
  1429. require.Equal(t, 200, response.Code)
  1430. m := toMessage(t, response.Body.String())
  1431. require.Equal(t, "", m.ContentType)
  1432. }
  1433. func TestServer_PublishAsJSON(t *testing.T) {
  1434. s := newTestServer(t, newTestConfig(t))
  1435. body := `{"topic":"mytopic","message":"A message","title":"a title\nwith lines","tags":["tag1","tag 2"],` +
  1436. `"not-a-thing":"ok", "attach":"http://google.com","filename":"google.pdf", "click":"http://ntfy.sh","priority":4,` +
  1437. `"icon":"https://ntfy.sh/static/img/ntfy.png", "delay":"30min"}`
  1438. response := request(t, s, "PUT", "/", body, nil)
  1439. require.Equal(t, 200, response.Code)
  1440. m := toMessage(t, response.Body.String())
  1441. require.Equal(t, "mytopic", m.Topic)
  1442. require.Equal(t, "A message", m.Message)
  1443. require.Equal(t, "a title\nwith lines", m.Title)
  1444. require.Equal(t, []string{"tag1", "tag 2"}, m.Tags)
  1445. require.Equal(t, "http://google.com", m.Attachment.URL)
  1446. require.Equal(t, "google.pdf", m.Attachment.Name)
  1447. require.Equal(t, "http://ntfy.sh", m.Click)
  1448. require.Equal(t, "https://ntfy.sh/static/img/ntfy.png", m.Icon)
  1449. require.Equal(t, "", m.ContentType)
  1450. require.Equal(t, 4, m.Priority)
  1451. require.True(t, m.Time > time.Now().Unix()+29*60)
  1452. require.True(t, m.Time < time.Now().Unix()+31*60)
  1453. }
  1454. func TestServer_PublishAsJSON_Markdown(t *testing.T) {
  1455. s := newTestServer(t, newTestConfig(t))
  1456. body := `{"topic":"mytopic","message":"**This is bold**","markdown":true}`
  1457. response := request(t, s, "PUT", "/", body, nil)
  1458. require.Equal(t, 200, response.Code)
  1459. m := toMessage(t, response.Body.String())
  1460. require.Equal(t, "mytopic", m.Topic)
  1461. require.Equal(t, "**This is bold**", m.Message)
  1462. require.Equal(t, "text/markdown", m.ContentType)
  1463. }
  1464. func TestServer_PublishAsJSON_RateLimit_MessageDailyLimit(t *testing.T) {
  1465. // Publishing as JSON follows a different path. This ensures that rate
  1466. // limiting works for this endpoint as well
  1467. c := newTestConfig(t)
  1468. c.VisitorMessageDailyLimit = 3
  1469. s := newTestServer(t, c)
  1470. for i := 0; i < 3; i++ {
  1471. response := request(t, s, "PUT", "/", `{"topic":"mytopic","message":"A message"}`, nil)
  1472. require.Equal(t, 200, response.Code)
  1473. }
  1474. response := request(t, s, "PUT", "/", `{"topic":"mytopic","message":"A message"}`, nil)
  1475. require.Equal(t, 429, response.Code)
  1476. require.Equal(t, 42908, toHTTPError(t, response.Body.String()).Code)
  1477. }
  1478. func TestServer_PublishAsJSON_WithEmail(t *testing.T) {
  1479. t.Parallel()
  1480. mailer := &testMailer{}
  1481. s := newTestServer(t, newTestConfig(t))
  1482. s.smtpSender = mailer
  1483. body := `{"topic":"mytopic","message":"A message","email":"phil@example.com"}`
  1484. response := request(t, s, "PUT", "/", body, nil)
  1485. require.Equal(t, 200, response.Code)
  1486. time.Sleep(100 * time.Millisecond) // E-Mail publishing happens in a Go routine
  1487. m := toMessage(t, response.Body.String())
  1488. require.Equal(t, "mytopic", m.Topic)
  1489. require.Equal(t, "A message", m.Message)
  1490. require.Equal(t, 1, mailer.Count())
  1491. }
  1492. func TestServer_PublishAsJSON_WithActions(t *testing.T) {
  1493. s := newTestServer(t, newTestConfig(t))
  1494. body := `{
  1495. "topic":"mytopic",
  1496. "message":"A message",
  1497. "actions": [
  1498. {
  1499. "action": "view",
  1500. "label": "Open portal",
  1501. "url": "https://home.nest.com/"
  1502. },
  1503. {
  1504. "action": "http",
  1505. "label": "Turn down",
  1506. "url": "https://api.nest.com/device/XZ1D2",
  1507. "body": "target_temp_f=65"
  1508. }
  1509. ]
  1510. }`
  1511. response := request(t, s, "POST", "/", body, nil)
  1512. require.Equal(t, 200, response.Code)
  1513. m := toMessage(t, response.Body.String())
  1514. require.Equal(t, "mytopic", m.Topic)
  1515. require.Equal(t, "A message", m.Message)
  1516. require.Equal(t, 2, len(m.Actions))
  1517. require.Equal(t, "view", m.Actions[0].Action)
  1518. require.Equal(t, "Open portal", m.Actions[0].Label)
  1519. require.Equal(t, "https://home.nest.com/", m.Actions[0].URL)
  1520. require.Equal(t, "http", m.Actions[1].Action)
  1521. require.Equal(t, "Turn down", m.Actions[1].Label)
  1522. require.Equal(t, "https://api.nest.com/device/XZ1D2", m.Actions[1].URL)
  1523. require.Equal(t, "target_temp_f=65", m.Actions[1].Body)
  1524. }
  1525. func TestServer_PublishAsJSON_NoCache(t *testing.T) {
  1526. s := newTestServer(t, newTestConfig(t))
  1527. body := `{"topic":"mytopic","message": "this message is not cached","cache":"no"}`
  1528. response := request(t, s, "PUT", "/", body, nil)
  1529. msg := toMessage(t, response.Body.String())
  1530. require.NotEmpty(t, msg.ID)
  1531. require.Equal(t, "this message is not cached", msg.Message)
  1532. require.Equal(t, int64(0), msg.Expires)
  1533. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  1534. messages := toMessages(t, response.Body.String())
  1535. require.Empty(t, messages)
  1536. }
  1537. func TestServer_PublishAsJSON_WithoutFirebase(t *testing.T) {
  1538. sender := newTestFirebaseSender(10)
  1539. s := newTestServer(t, newTestConfig(t))
  1540. s.firebaseClient = newFirebaseClient(sender, &testAuther{Allow: true})
  1541. body := `{"topic":"mytopic","message": "my first message","firebase":"no"}`
  1542. response := request(t, s, "PUT", "/", body, nil)
  1543. msg1 := toMessage(t, response.Body.String())
  1544. require.NotEmpty(t, msg1.ID)
  1545. require.Equal(t, "my first message", msg1.Message)
  1546. time.Sleep(100 * time.Millisecond) // Firebase publishing happens
  1547. require.Equal(t, 0, len(sender.Messages()))
  1548. }
  1549. func TestServer_PublishAsJSON_Invalid(t *testing.T) {
  1550. s := newTestServer(t, newTestConfig(t))
  1551. body := `{"topic":"mytopic",INVALID`
  1552. response := request(t, s, "PUT", "/", body, nil)
  1553. require.Equal(t, 400, response.Code)
  1554. }
  1555. func TestServer_PublishWithTierBasedMessageLimitAndExpiry(t *testing.T) {
  1556. c := newTestConfigWithAuthFile(t)
  1557. s := newTestServer(t, c)
  1558. // Create tier with certain limits
  1559. require.Nil(t, s.userManager.AddTier(&user.Tier{
  1560. Code: "test",
  1561. MessageLimit: 5,
  1562. MessageExpiryDuration: -5 * time.Second, // Second, what a hack!
  1563. }))
  1564. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser, false))
  1565. require.Nil(t, s.userManager.ChangeTier("phil", "test"))
  1566. // Publish to reach message limit
  1567. for i := 0; i < 5; i++ {
  1568. response := request(t, s, "PUT", "/mytopic", fmt.Sprintf("this is message %d", i+1), map[string]string{
  1569. "Authorization": util.BasicAuth("phil", "phil"),
  1570. })
  1571. require.Equal(t, 200, response.Code)
  1572. msg := toMessage(t, response.Body.String())
  1573. require.True(t, msg.Expires < time.Now().Unix()+5)
  1574. }
  1575. response := request(t, s, "PUT", "/mytopic", "this is too much", map[string]string{
  1576. "Authorization": util.BasicAuth("phil", "phil"),
  1577. })
  1578. require.Equal(t, 429, response.Code)
  1579. // Run pruning and see if they are gone
  1580. s.execManager()
  1581. response = request(t, s, "GET", "/mytopic/json?poll=1", "", map[string]string{
  1582. "Authorization": util.BasicAuth("phil", "phil"),
  1583. })
  1584. require.Equal(t, 200, response.Code)
  1585. require.Empty(t, response.Body)
  1586. }
  1587. func TestServer_PublishAttachment(t *testing.T) {
  1588. content := "text file!" + util.RandomString(4990) // > 4096
  1589. s := newTestServer(t, newTestConfig(t))
  1590. response := request(t, s, "PUT", "/mytopic", content, nil)
  1591. msg := toMessage(t, response.Body.String())
  1592. require.Equal(t, "attachment.txt", msg.Attachment.Name)
  1593. require.Equal(t, "text/plain; charset=utf-8", msg.Attachment.Type)
  1594. require.Equal(t, int64(5000), msg.Attachment.Size)
  1595. require.GreaterOrEqual(t, msg.Attachment.Expires, time.Now().Add(179*time.Minute).Unix()) // Almost 3 hours
  1596. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1597. require.Equal(t, netip.Addr{}, msg.Sender) // Should never be returned
  1598. require.FileExists(t, filepath.Join(s.config.AttachmentCacheDir, msg.ID))
  1599. // GET
  1600. path := strings.TrimPrefix(msg.Attachment.URL, "http://127.0.0.1:12345")
  1601. response = request(t, s, "GET", path, "", nil)
  1602. require.Equal(t, 200, response.Code)
  1603. require.Equal(t, "5000", response.Header().Get("Content-Length"))
  1604. require.Equal(t, content, response.Body.String())
  1605. // HEAD
  1606. response = request(t, s, "HEAD", path, "", nil)
  1607. require.Equal(t, 200, response.Code)
  1608. require.Equal(t, "5000", response.Header().Get("Content-Length"))
  1609. require.Equal(t, "", response.Body.String())
  1610. // Slightly unrelated cross-test: make sure we add an owner for internal attachments
  1611. size, err := s.messageCache.AttachmentBytesUsedBySender("9.9.9.9") // See request()
  1612. require.Nil(t, err)
  1613. require.Equal(t, int64(5000), size)
  1614. }
  1615. func TestServer_PublishAttachmentShortWithFilename(t *testing.T) {
  1616. c := newTestConfig(t)
  1617. c.BehindProxy = true
  1618. s := newTestServer(t, c)
  1619. content := "this is an ATTACHMENT"
  1620. response := request(t, s, "PUT", "/mytopic?f=myfile.txt", content, map[string]string{
  1621. "X-Forwarded-For": "1.2.3.4",
  1622. })
  1623. msg := toMessage(t, response.Body.String())
  1624. require.Equal(t, "myfile.txt", msg.Attachment.Name)
  1625. require.Equal(t, "text/plain; charset=utf-8", msg.Attachment.Type)
  1626. require.Equal(t, int64(21), msg.Attachment.Size)
  1627. require.GreaterOrEqual(t, msg.Attachment.Expires, time.Now().Add(3*time.Hour).Unix())
  1628. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1629. require.Equal(t, netip.Addr{}, msg.Sender) // Should never be returned
  1630. require.FileExists(t, filepath.Join(s.config.AttachmentCacheDir, msg.ID))
  1631. path := strings.TrimPrefix(msg.Attachment.URL, "http://127.0.0.1:12345")
  1632. response = request(t, s, "GET", path, "", nil)
  1633. require.Equal(t, 200, response.Code)
  1634. require.Equal(t, "21", response.Header().Get("Content-Length"))
  1635. require.Equal(t, content, response.Body.String())
  1636. // Slightly unrelated cross-test: make sure we add an owner for internal attachments
  1637. size, err := s.messageCache.AttachmentBytesUsedBySender("1.2.3.4")
  1638. require.Nil(t, err)
  1639. require.Equal(t, int64(21), size)
  1640. }
  1641. func TestServer_PublishAttachmentExternalWithoutFilename(t *testing.T) {
  1642. s := newTestServer(t, newTestConfig(t))
  1643. response := request(t, s, "PUT", "/mytopic", "", map[string]string{
  1644. "Attach": "https://upload.wikimedia.org/wikipedia/commons/f/fd/Pink_flower.jpg",
  1645. })
  1646. msg := toMessage(t, response.Body.String())
  1647. require.Equal(t, "You received a file: Pink_flower.jpg", msg.Message)
  1648. require.Equal(t, "Pink_flower.jpg", msg.Attachment.Name)
  1649. require.Equal(t, "https://upload.wikimedia.org/wikipedia/commons/f/fd/Pink_flower.jpg", msg.Attachment.URL)
  1650. require.Equal(t, "", msg.Attachment.Type)
  1651. require.Equal(t, int64(0), msg.Attachment.Size)
  1652. require.Equal(t, int64(0), msg.Attachment.Expires)
  1653. require.Equal(t, netip.Addr{}, msg.Sender)
  1654. // Slightly unrelated cross-test: make sure we don't add an owner for external attachments
  1655. size, err := s.messageCache.AttachmentBytesUsedBySender("127.0.0.1")
  1656. require.Nil(t, err)
  1657. require.Equal(t, int64(0), size)
  1658. }
  1659. func TestServer_PublishAttachmentExternalWithFilename(t *testing.T) {
  1660. s := newTestServer(t, newTestConfig(t))
  1661. response := request(t, s, "PUT", "/mytopic", "This is a custom message", map[string]string{
  1662. "X-Attach": "https://upload.wikimedia.org/wikipedia/commons/f/fd/Pink_flower.jpg",
  1663. "File": "some file.jpg",
  1664. })
  1665. msg := toMessage(t, response.Body.String())
  1666. require.Equal(t, "This is a custom message", msg.Message)
  1667. require.Equal(t, "some file.jpg", msg.Attachment.Name)
  1668. require.Equal(t, "https://upload.wikimedia.org/wikipedia/commons/f/fd/Pink_flower.jpg", msg.Attachment.URL)
  1669. require.Equal(t, "", msg.Attachment.Type)
  1670. require.Equal(t, int64(0), msg.Attachment.Size)
  1671. require.Equal(t, int64(0), msg.Attachment.Expires)
  1672. require.Equal(t, netip.Addr{}, msg.Sender)
  1673. }
  1674. func TestServer_PublishAttachmentBadURL(t *testing.T) {
  1675. s := newTestServer(t, newTestConfig(t))
  1676. response := request(t, s, "PUT", "/mytopic?a=not+a+URL", "", nil)
  1677. err := toHTTPError(t, response.Body.String())
  1678. require.Equal(t, 400, response.Code)
  1679. require.Equal(t, 400, err.HTTPCode)
  1680. require.Equal(t, 40013, err.Code)
  1681. }
  1682. func TestServer_PublishAttachmentTooLargeContentLength(t *testing.T) {
  1683. content := util.RandomString(5000) // > 4096
  1684. s := newTestServer(t, newTestConfig(t))
  1685. response := request(t, s, "PUT", "/mytopic", content, map[string]string{
  1686. "Content-Length": "20000000",
  1687. })
  1688. err := toHTTPError(t, response.Body.String())
  1689. require.Equal(t, 413, response.Code)
  1690. require.Equal(t, 413, err.HTTPCode)
  1691. require.Equal(t, 41301, err.Code)
  1692. }
  1693. func TestServer_PublishAttachmentTooLargeBodyAttachmentFileSizeLimit(t *testing.T) {
  1694. content := util.RandomString(5001) // > 5000, see below
  1695. c := newTestConfig(t)
  1696. c.AttachmentFileSizeLimit = 5000
  1697. s := newTestServer(t, c)
  1698. response := request(t, s, "PUT", "/mytopic", content, nil)
  1699. err := toHTTPError(t, response.Body.String())
  1700. require.Equal(t, 413, response.Code)
  1701. require.Equal(t, 413, err.HTTPCode)
  1702. require.Equal(t, 41301, err.Code)
  1703. }
  1704. func TestServer_PublishAttachmentExpiryBeforeDelivery(t *testing.T) {
  1705. c := newTestConfig(t)
  1706. c.AttachmentExpiryDuration = 10 * time.Minute
  1707. s := newTestServer(t, c)
  1708. response := request(t, s, "PUT", "/mytopic", util.RandomString(5000), map[string]string{
  1709. "Delay": "11 min", // > AttachmentExpiryDuration
  1710. })
  1711. err := toHTTPError(t, response.Body.String())
  1712. require.Equal(t, 400, response.Code)
  1713. require.Equal(t, 400, err.HTTPCode)
  1714. require.Equal(t, 40015, err.Code)
  1715. }
  1716. func TestServer_PublishAttachmentTooLargeBodyVisitorAttachmentTotalSizeLimit(t *testing.T) {
  1717. c := newTestConfig(t)
  1718. c.VisitorAttachmentTotalSizeLimit = 10000
  1719. s := newTestServer(t, c)
  1720. response := request(t, s, "PUT", "/mytopic", "text file!"+util.RandomString(4990), nil)
  1721. msg := toMessage(t, response.Body.String())
  1722. require.Equal(t, 200, response.Code)
  1723. require.Equal(t, "You received a file: attachment.txt", msg.Message)
  1724. require.Equal(t, int64(5000), msg.Attachment.Size)
  1725. content := util.RandomString(5001) // 5000+5001 > , see below
  1726. response = request(t, s, "PUT", "/mytopic", content, nil)
  1727. err := toHTTPError(t, response.Body.String())
  1728. require.Equal(t, 413, response.Code)
  1729. require.Equal(t, 413, err.HTTPCode)
  1730. require.Equal(t, 41301, err.Code)
  1731. }
  1732. func TestServer_PublishAttachmentAndExpire(t *testing.T) {
  1733. t.Parallel()
  1734. content := util.RandomString(5000) // > 4096
  1735. c := newTestConfig(t)
  1736. c.AttachmentExpiryDuration = time.Millisecond // Hack
  1737. s := newTestServer(t, c)
  1738. // Publish and make sure we can retrieve it
  1739. response := request(t, s, "PUT", "/mytopic", content, nil)
  1740. msg := toMessage(t, response.Body.String())
  1741. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1742. file := filepath.Join(s.config.AttachmentCacheDir, msg.ID)
  1743. require.FileExists(t, file)
  1744. path := strings.TrimPrefix(msg.Attachment.URL, "http://127.0.0.1:12345")
  1745. response = request(t, s, "GET", path, "", nil)
  1746. require.Equal(t, 200, response.Code)
  1747. require.Equal(t, content, response.Body.String())
  1748. // Prune and makes sure it's gone
  1749. waitFor(t, func() bool {
  1750. s.execManager() // May run many times
  1751. return !util.FileExists(file)
  1752. })
  1753. response = request(t, s, "GET", path, "", nil)
  1754. require.Equal(t, 404, response.Code)
  1755. }
  1756. func TestServer_PublishAttachmentWithTierBasedExpiry(t *testing.T) {
  1757. t.Parallel()
  1758. content := util.RandomString(5000) // > 4096
  1759. c := newTestConfigWithAuthFile(t)
  1760. c.AttachmentExpiryDuration = time.Millisecond // Hack
  1761. s := newTestServer(t, c)
  1762. // Create tier with certain limits
  1763. sevenDays := time.Duration(604800) * time.Second
  1764. require.Nil(t, s.userManager.AddTier(&user.Tier{
  1765. Code: "test",
  1766. MessageLimit: 10,
  1767. MessageExpiryDuration: sevenDays,
  1768. AttachmentFileSizeLimit: 50_000,
  1769. AttachmentTotalSizeLimit: 200_000,
  1770. AttachmentExpiryDuration: sevenDays, // 7 days
  1771. AttachmentBandwidthLimit: 100000,
  1772. }))
  1773. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser, false))
  1774. require.Nil(t, s.userManager.ChangeTier("phil", "test"))
  1775. // Publish and make sure we can retrieve it
  1776. response := request(t, s, "PUT", "/mytopic", content, map[string]string{
  1777. "Authorization": util.BasicAuth("phil", "phil"),
  1778. })
  1779. require.Equal(t, 200, response.Code)
  1780. msg := toMessage(t, response.Body.String())
  1781. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1782. require.True(t, msg.Attachment.Expires > time.Now().Add(sevenDays-30*time.Second).Unix())
  1783. require.True(t, msg.Expires > time.Now().Add(sevenDays-30*time.Second).Unix())
  1784. file := filepath.Join(s.config.AttachmentCacheDir, msg.ID)
  1785. require.FileExists(t, file)
  1786. path := strings.TrimPrefix(msg.Attachment.URL, "http://127.0.0.1:12345")
  1787. response = request(t, s, "GET", path, "", nil)
  1788. require.Equal(t, 200, response.Code)
  1789. require.Equal(t, content, response.Body.String())
  1790. // Prune and makes sure it's still there
  1791. time.Sleep(time.Second) // Sigh ...
  1792. s.execManager()
  1793. require.FileExists(t, file)
  1794. response = request(t, s, "GET", path, "", nil)
  1795. require.Equal(t, 200, response.Code)
  1796. }
  1797. func TestServer_PublishAttachmentWithTierBasedBandwidthLimit(t *testing.T) {
  1798. content := util.RandomString(5000) // > 4096
  1799. c := newTestConfigWithAuthFile(t)
  1800. c.VisitorAttachmentDailyBandwidthLimit = 1000 // Much lower than tier bandwidth!
  1801. s := newTestServer(t, c)
  1802. // Create tier with certain limits
  1803. require.Nil(t, s.userManager.AddTier(&user.Tier{
  1804. Code: "test",
  1805. MessageLimit: 10,
  1806. MessageExpiryDuration: time.Hour,
  1807. AttachmentFileSizeLimit: 50_000,
  1808. AttachmentTotalSizeLimit: 200_000,
  1809. AttachmentExpiryDuration: time.Hour,
  1810. AttachmentBandwidthLimit: 14000, // < 3x5000 bytes -> enough for one upload, one download
  1811. }))
  1812. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser, false))
  1813. require.Nil(t, s.userManager.ChangeTier("phil", "test"))
  1814. // Publish and make sure we can retrieve it
  1815. rr := request(t, s, "PUT", "/mytopic", content, map[string]string{
  1816. "Authorization": util.BasicAuth("phil", "phil"),
  1817. })
  1818. require.Equal(t, 200, rr.Code)
  1819. msg := toMessage(t, rr.Body.String())
  1820. // Retrieve it (first time succeeds)
  1821. rr = request(t, s, "GET", "/file/"+msg.ID, content, nil) // File downloads do not send auth headers!!
  1822. require.Equal(t, 200, rr.Code)
  1823. require.Equal(t, content, rr.Body.String())
  1824. // Retrieve it AGAIN (fails, due to bandwidth limit)
  1825. rr = request(t, s, "GET", "/file/"+msg.ID, content, nil)
  1826. require.Equal(t, 429, rr.Code)
  1827. }
  1828. func TestServer_PublishAttachmentWithTierBasedLimits(t *testing.T) {
  1829. smallFile := util.RandomString(20_000)
  1830. largeFile := util.RandomString(50_000)
  1831. c := newTestConfigWithAuthFile(t)
  1832. c.AttachmentFileSizeLimit = 20_000
  1833. c.VisitorAttachmentTotalSizeLimit = 40_000
  1834. s := newTestServer(t, c)
  1835. // Create tier with certain limits
  1836. require.Nil(t, s.userManager.AddTier(&user.Tier{
  1837. Code: "test",
  1838. MessageLimit: 100,
  1839. AttachmentFileSizeLimit: 50_000,
  1840. AttachmentTotalSizeLimit: 200_000,
  1841. AttachmentExpiryDuration: 30 * time.Second,
  1842. AttachmentBandwidthLimit: 1000000,
  1843. }))
  1844. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser, false))
  1845. require.Nil(t, s.userManager.ChangeTier("phil", "test"))
  1846. // Publish small file as anonymous
  1847. response := request(t, s, "PUT", "/mytopic", smallFile, nil)
  1848. msg := toMessage(t, response.Body.String())
  1849. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1850. require.FileExists(t, filepath.Join(s.config.AttachmentCacheDir, msg.ID))
  1851. // Publish large file as anonymous
  1852. response = request(t, s, "PUT", "/mytopic", largeFile, nil)
  1853. require.Equal(t, 413, response.Code)
  1854. require.Equal(t, 41301, toHTTPError(t, response.Body.String()).Code)
  1855. // Publish too large file as phil
  1856. response = request(t, s, "PUT", "/mytopic", largeFile+" a few more bytes", map[string]string{
  1857. "Authorization": util.BasicAuth("phil", "phil"),
  1858. })
  1859. require.Equal(t, 413, response.Code)
  1860. require.Equal(t, 41301, toHTTPError(t, response.Body.String()).Code)
  1861. // Publish large file as phil (4x)
  1862. for i := 0; i < 4; i++ {
  1863. response = request(t, s, "PUT", "/mytopic", largeFile, map[string]string{
  1864. "Authorization": util.BasicAuth("phil", "phil"),
  1865. })
  1866. require.Equal(t, 200, response.Code)
  1867. msg = toMessage(t, response.Body.String())
  1868. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1869. require.FileExists(t, filepath.Join(s.config.AttachmentCacheDir, msg.ID))
  1870. }
  1871. response = request(t, s, "PUT", "/mytopic", largeFile, map[string]string{
  1872. "Authorization": util.BasicAuth("phil", "phil"),
  1873. })
  1874. require.Equal(t, 413, response.Code)
  1875. require.Equal(t, 41301, toHTTPError(t, response.Body.String()).Code)
  1876. }
  1877. func TestServer_PublishAttachmentBandwidthLimit(t *testing.T) {
  1878. content := util.RandomString(5000) // > 4096
  1879. c := newTestConfig(t)
  1880. c.VisitorAttachmentDailyBandwidthLimit = 5*5000 + 123 // A little more than 1 upload and 3 downloads
  1881. s := newTestServer(t, c)
  1882. // Publish attachment
  1883. response := request(t, s, "PUT", "/mytopic", content, nil)
  1884. msg := toMessage(t, response.Body.String())
  1885. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1886. // Value it 4 times successfully
  1887. path := strings.TrimPrefix(msg.Attachment.URL, "http://127.0.0.1:12345")
  1888. for i := 1; i <= 4; i++ { // 4 successful downloads
  1889. response = request(t, s, "GET", path, "", nil)
  1890. require.Equal(t, 200, response.Code)
  1891. require.Equal(t, content, response.Body.String())
  1892. }
  1893. // And then fail with a 429
  1894. response = request(t, s, "GET", path, "", nil)
  1895. err := toHTTPError(t, response.Body.String())
  1896. require.Equal(t, 429, response.Code)
  1897. require.Equal(t, 42905, err.Code)
  1898. }
  1899. func TestServer_PublishAttachmentBandwidthLimitUploadOnly(t *testing.T) {
  1900. content := util.RandomString(5000) // > 4096
  1901. c := newTestConfig(t)
  1902. c.VisitorAttachmentDailyBandwidthLimit = 5*5000 + 500 // 5 successful uploads
  1903. s := newTestServer(t, c)
  1904. // 5 successful uploads
  1905. for i := 1; i <= 5; i++ {
  1906. response := request(t, s, "PUT", "/mytopic", content, nil)
  1907. msg := toMessage(t, response.Body.String())
  1908. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1909. }
  1910. // And a failed one
  1911. response := request(t, s, "PUT", "/mytopic", content, nil)
  1912. err := toHTTPError(t, response.Body.String())
  1913. require.Equal(t, 413, response.Code)
  1914. require.Equal(t, 41301, err.Code)
  1915. }
  1916. func TestServer_PublishAttachmentAndImmediatelyGetItWithCacheTimeout(t *testing.T) {
  1917. // This tests the awkward util.Retry in handleFile: Due to the async persisting of messages,
  1918. // the message is not immediately available when attempting to download it.
  1919. c := newTestConfig(t)
  1920. c.CacheBatchTimeout = 500 * time.Millisecond
  1921. c.CacheBatchSize = 10
  1922. s := newTestServer(t, c)
  1923. content := "this is an ATTACHMENT"
  1924. rr := request(t, s, "PUT", "/mytopic?f=myfile.txt", content, nil)
  1925. m := toMessage(t, rr.Body.String())
  1926. require.Equal(t, "myfile.txt", m.Attachment.Name)
  1927. path := strings.TrimPrefix(m.Attachment.URL, "http://127.0.0.1:12345")
  1928. rr = request(t, s, "GET", path, "", nil)
  1929. require.Equal(t, 200, rr.Code) // Not 404!
  1930. require.Equal(t, content, rr.Body.String())
  1931. }
  1932. func TestServer_PublishAttachmentAccountStats(t *testing.T) {
  1933. content := util.RandomString(4999) // > 4096
  1934. c := newTestConfig(t)
  1935. c.AttachmentFileSizeLimit = 5000
  1936. c.VisitorAttachmentTotalSizeLimit = 6000
  1937. s := newTestServer(t, c)
  1938. // Upload one attachment
  1939. response := request(t, s, "PUT", "/mytopic", content, nil)
  1940. msg := toMessage(t, response.Body.String())
  1941. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1942. // User stats
  1943. response = request(t, s, "GET", "/v1/account", "", nil)
  1944. require.Equal(t, 200, response.Code)
  1945. account, err := util.UnmarshalJSON[apiAccountResponse](io.NopCloser(response.Body))
  1946. require.Nil(t, err)
  1947. require.Equal(t, int64(5000), account.Limits.AttachmentFileSize)
  1948. require.Equal(t, int64(6000), account.Limits.AttachmentTotalSize)
  1949. require.Equal(t, int64(4999), account.Stats.AttachmentTotalSize)
  1950. require.Equal(t, int64(1001), account.Stats.AttachmentTotalSizeRemaining)
  1951. require.Equal(t, int64(1), account.Stats.Messages)
  1952. }
  1953. func TestServer_Visitor_XForwardedFor_None(t *testing.T) {
  1954. c := newTestConfig(t)
  1955. c.BehindProxy = true
  1956. s := newTestServer(t, c)
  1957. r, _ := http.NewRequest("GET", "/bla", nil)
  1958. r.RemoteAddr = "8.9.10.11:1234"
  1959. r.Header.Set("X-Forwarded-For", " ") // Spaces, not empty!
  1960. v, err := s.maybeAuthenticate(r)
  1961. require.Nil(t, err)
  1962. require.Equal(t, "8.9.10.11", v.ip.String())
  1963. }
  1964. func TestServer_Visitor_XForwardedFor_Single(t *testing.T) {
  1965. c := newTestConfig(t)
  1966. c.BehindProxy = true
  1967. s := newTestServer(t, c)
  1968. r, _ := http.NewRequest("GET", "/bla", nil)
  1969. r.RemoteAddr = "8.9.10.11:1234"
  1970. r.Header.Set("X-Forwarded-For", "1.1.1.1")
  1971. v, err := s.maybeAuthenticate(r)
  1972. require.Nil(t, err)
  1973. require.Equal(t, "1.1.1.1", v.ip.String())
  1974. }
  1975. func TestServer_Visitor_XForwardedFor_Multiple(t *testing.T) {
  1976. c := newTestConfig(t)
  1977. c.BehindProxy = true
  1978. s := newTestServer(t, c)
  1979. r, _ := http.NewRequest("GET", "/bla", nil)
  1980. r.RemoteAddr = "8.9.10.11:1234"
  1981. r.Header.Set("X-Forwarded-For", "1.2.3.4 , 2.4.4.2,234.5.2.1 ")
  1982. v, err := s.maybeAuthenticate(r)
  1983. require.Nil(t, err)
  1984. require.Equal(t, "234.5.2.1", v.ip.String())
  1985. }
  1986. func TestServer_Visitor_Custom_ClientIP_Header(t *testing.T) {
  1987. c := newTestConfig(t)
  1988. c.BehindProxy = true
  1989. c.ProxyForwardedHeader = "X-Client-IP"
  1990. s := newTestServer(t, c)
  1991. r, _ := http.NewRequest("GET", "/bla", nil)
  1992. r.RemoteAddr = "8.9.10.11:1234"
  1993. r.Header.Set("X-Client-IP", "1.2.3.4")
  1994. v, err := s.maybeAuthenticate(r)
  1995. require.Nil(t, err)
  1996. require.Equal(t, "1.2.3.4", v.ip.String())
  1997. }
  1998. func TestServer_Visitor_Custom_ClientIP_Header_IPv6(t *testing.T) {
  1999. c := newTestConfig(t)
  2000. c.BehindProxy = true
  2001. c.ProxyForwardedHeader = "X-Client-IP"
  2002. s := newTestServer(t, c)
  2003. r, _ := http.NewRequest("GET", "/bla", nil)
  2004. r.RemoteAddr = "[2001:db8:9999::1]:1234"
  2005. r.Header.Set("X-Client-IP", "2001:db8:7777::1")
  2006. v, err := s.maybeAuthenticate(r)
  2007. require.Nil(t, err)
  2008. require.Equal(t, "2001:db8:7777::1", v.ip.String())
  2009. }
  2010. func TestServer_Visitor_Custom_Forwarded_Header(t *testing.T) {
  2011. c := newTestConfig(t)
  2012. c.BehindProxy = true
  2013. c.ProxyForwardedHeader = "Forwarded"
  2014. c.ProxyTrustedPrefixes = []netip.Prefix{netip.MustParsePrefix("1.2.3.0/24")}
  2015. s := newTestServer(t, c)
  2016. r, _ := http.NewRequest("GET", "/bla", nil)
  2017. r.RemoteAddr = "8.9.10.11:1234"
  2018. r.Header.Set("Forwarded", " for=5.6.7.8, by=example.com;for=1.2.3.4")
  2019. v, err := s.maybeAuthenticate(r)
  2020. require.Nil(t, err)
  2021. require.Equal(t, "5.6.7.8", v.ip.String())
  2022. }
  2023. func TestServer_Visitor_Custom_Forwarded_Header_IPv6(t *testing.T) {
  2024. c := newTestConfig(t)
  2025. c.BehindProxy = true
  2026. c.ProxyForwardedHeader = "Forwarded"
  2027. c.ProxyTrustedPrefixes = []netip.Prefix{netip.MustParsePrefix("2001:db8:1111::/64")}
  2028. s := newTestServer(t, c)
  2029. r, _ := http.NewRequest("GET", "/bla", nil)
  2030. r.RemoteAddr = "[2001:db8:2222::1]:1234"
  2031. r.Header.Set("Forwarded", " for=[2001:db8:1111::1], by=example.com;for=[2001:db8:3333::1]")
  2032. v, err := s.maybeAuthenticate(r)
  2033. require.Nil(t, err)
  2034. require.Equal(t, "2001:db8:3333::1", v.ip.String())
  2035. }
  2036. func TestServer_PublishWhileUpdatingStatsWithLotsOfMessages(t *testing.T) {
  2037. t.Parallel()
  2038. count := 50000
  2039. c := newTestConfig(t)
  2040. c.TotalTopicLimit = 50001
  2041. c.CacheStartupQueries = "pragma journal_mode = WAL; pragma synchronous = normal; pragma temp_store = memory;"
  2042. s := newTestServer(t, c)
  2043. // Add lots of messages
  2044. log.Info("Adding %d messages", count)
  2045. start := time.Now()
  2046. messages := make([]*message, 0)
  2047. for i := 0; i < count; i++ {
  2048. topicID := fmt.Sprintf("topic%d", i)
  2049. _, err := s.topicsFromIDs(topicID) // Add topic to internal s.topics array
  2050. require.Nil(t, err)
  2051. messages = append(messages, newDefaultMessage(topicID, "some message"))
  2052. }
  2053. require.Nil(t, s.messageCache.addMessages(messages))
  2054. log.Info("Done: Adding %d messages; took %s", count, time.Since(start).Round(time.Millisecond))
  2055. // Update stats
  2056. statsChan := make(chan bool)
  2057. go func() {
  2058. log.Info("Updating stats")
  2059. start := time.Now()
  2060. s.execManager()
  2061. log.Info("Done: Updating stats; took %s", time.Since(start).Round(time.Millisecond))
  2062. statsChan <- true
  2063. }()
  2064. time.Sleep(50 * time.Millisecond) // Make sure it starts first
  2065. // Publish message (during stats update)
  2066. log.Info("Publishing message")
  2067. start = time.Now()
  2068. response := request(t, s, "PUT", "/mytopic", "some body", nil)
  2069. m := toMessage(t, response.Body.String())
  2070. require.Equal(t, "some body", m.Message)
  2071. require.True(t, time.Since(start) < 100*time.Millisecond)
  2072. log.Info("Done: Publishing message; took %s", time.Since(start).Round(time.Millisecond))
  2073. // Wait for all goroutines
  2074. select {
  2075. case <-statsChan:
  2076. case <-time.After(10 * time.Second):
  2077. t.Fatal("Timed out waiting for Go routines")
  2078. }
  2079. log.Info("Done: Waiting for all locks")
  2080. }
  2081. func TestServer_AnonymousUser_And_NonTierUser_Are_Same_Visitor(t *testing.T) {
  2082. conf := newTestConfigWithAuthFile(t)
  2083. s := newTestServer(t, conf)
  2084. defer s.closeDatabases()
  2085. // Create user without tier
  2086. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser, false))
  2087. // Publish a message (anonymous user)
  2088. rr := request(t, s, "POST", "/mytopic", "hi", nil)
  2089. require.Equal(t, 200, rr.Code)
  2090. // Publish a message (non-tier user)
  2091. rr = request(t, s, "POST", "/mytopic", "hi", map[string]string{
  2092. "Authorization": util.BasicAuth("phil", "phil"),
  2093. })
  2094. require.Equal(t, 200, rr.Code)
  2095. // User stats (anonymous user)
  2096. rr = request(t, s, "GET", "/v1/account", "", nil)
  2097. account, _ := util.UnmarshalJSON[apiAccountResponse](io.NopCloser(rr.Body))
  2098. require.Equal(t, int64(2), account.Stats.Messages)
  2099. // User stats (non-tier user)
  2100. rr = request(t, s, "GET", "/v1/account", "", map[string]string{
  2101. "Authorization": util.BasicAuth("phil", "phil"),
  2102. })
  2103. account, _ = util.UnmarshalJSON[apiAccountResponse](io.NopCloser(rr.Body))
  2104. require.Equal(t, int64(2), account.Stats.Messages)
  2105. }
  2106. func TestServer_SubscriberRateLimiting_Success(t *testing.T) {
  2107. c := newTestConfigWithAuthFile(t)
  2108. c.VisitorRequestLimitBurst = 3
  2109. c.VisitorSubscriberRateLimiting = true
  2110. s := newTestServer(t, c)
  2111. // "Register" visitor 1.2.3.4 to topic "upAAAAAAAAAAAA" as a rate limit visitor
  2112. subscriber1Fn := func(r *http.Request) {
  2113. r.RemoteAddr = "1.2.3.4:1234"
  2114. }
  2115. rr := request(t, s, "GET", "/upAAAAAAAAAAAA/json?poll=1", "", nil, subscriber1Fn)
  2116. require.Equal(t, 200, rr.Code)
  2117. require.Equal(t, "", rr.Body.String())
  2118. require.Equal(t, "1.2.3.4", s.topics["upAAAAAAAAAAAA"].rateVisitor.ip.String())
  2119. // "Register" visitor 8.7.7.1 to topic "up012345678912" as a rate limit visitor (implicitly via topic name)
  2120. subscriber2Fn := func(r *http.Request) {
  2121. r.RemoteAddr = "8.7.7.1:1234"
  2122. }
  2123. rr = request(t, s, "GET", "/up012345678912/json?poll=1", "", nil, subscriber2Fn)
  2124. require.Equal(t, 200, rr.Code)
  2125. require.Equal(t, "", rr.Body.String())
  2126. require.Equal(t, "8.7.7.1", s.topics["up012345678912"].rateVisitor.ip.String())
  2127. // Publish 2 messages to "subscriber1topic" as visitor 9.9.9.9. It'd be 3 normally, but the
  2128. // GET request before is also counted towards the request limiter.
  2129. for i := 0; i < 2; i++ {
  2130. rr := request(t, s, "PUT", "/upAAAAAAAAAAAA", "some message", nil)
  2131. require.Equal(t, 200, rr.Code)
  2132. }
  2133. rr = request(t, s, "PUT", "/upAAAAAAAAAAAA", "some message", nil)
  2134. require.Equal(t, 429, rr.Code)
  2135. // Publish another 2 messages to "up012345678912" as visitor 9.9.9.9
  2136. for i := 0; i < 2; i++ {
  2137. rr := request(t, s, "PUT", "/up012345678912", "some message", nil)
  2138. require.Equal(t, 200, rr.Code) // If we fail here, handlePublish is using the wrong visitor!
  2139. }
  2140. rr = request(t, s, "PUT", "/up012345678912", "some message", nil)
  2141. require.Equal(t, 429, rr.Code)
  2142. // Hurray! At this point, visitor 9.9.9.9 has published 4 messages, even though
  2143. // VisitorRequestLimitBurst is 3. That means it's working.
  2144. // Now let's confirm that so far we haven't used up any of visitor 9.9.9.9's request limiter
  2145. // by publishing another 3 requests from it.
  2146. for i := 0; i < 3; i++ {
  2147. rr := request(t, s, "PUT", "/some-other-topic", "some message", nil)
  2148. require.Equal(t, 200, rr.Code)
  2149. }
  2150. rr = request(t, s, "PUT", "/some-other-topic", "some message", nil)
  2151. require.Equal(t, 429, rr.Code)
  2152. }
  2153. func TestServer_SubscriberRateLimiting_NotWrongTopic(t *testing.T) {
  2154. c := newTestConfigWithAuthFile(t)
  2155. c.VisitorSubscriberRateLimiting = true
  2156. s := newTestServer(t, c)
  2157. subscriberFn := func(r *http.Request) {
  2158. r.RemoteAddr = "1.2.3.4:1234"
  2159. }
  2160. rr := request(t, s, "GET", "/alerts,upAAAAAAAAAAAA,upBBBBBBBBBBBB/json?poll=1", "", nil, subscriberFn)
  2161. require.Equal(t, 200, rr.Code)
  2162. require.Equal(t, "", rr.Body.String())
  2163. require.Nil(t, s.topics["alerts"].rateVisitor)
  2164. require.Equal(t, "1.2.3.4", s.topics["upAAAAAAAAAAAA"].rateVisitor.ip.String())
  2165. require.Equal(t, "1.2.3.4", s.topics["upBBBBBBBBBBBB"].rateVisitor.ip.String())
  2166. }
  2167. func TestServer_SubscriberRateLimiting_NotEnabled_Failed(t *testing.T) {
  2168. c := newTestConfigWithAuthFile(t)
  2169. c.VisitorRequestLimitBurst = 3
  2170. c.VisitorSubscriberRateLimiting = false
  2171. s := newTestServer(t, c)
  2172. // Subscriber rate limiting is disabled!
  2173. // Registering visitor 1.2.3.4 to topic has no effect
  2174. rr := request(t, s, "GET", "/upAAAAAAAAAAAA/json?poll=1", "", nil, func(r *http.Request) {
  2175. r.RemoteAddr = "1.2.3.4:1234"
  2176. })
  2177. require.Equal(t, 200, rr.Code)
  2178. require.Equal(t, "", rr.Body.String())
  2179. require.Nil(t, s.topics["upAAAAAAAAAAAA"].rateVisitor)
  2180. // Registering visitor 8.7.7.1 to topic has no effect
  2181. rr = request(t, s, "GET", "/up012345678912/json?poll=1", "", nil, func(r *http.Request) {
  2182. r.RemoteAddr = "8.7.7.1:1234"
  2183. })
  2184. require.Equal(t, 200, rr.Code)
  2185. require.Equal(t, "", rr.Body.String())
  2186. require.Nil(t, s.topics["up012345678912"].rateVisitor)
  2187. // Publish 3 messages to "upAAAAAAAAAAAA" as visitor 9.9.9.9
  2188. for i := 0; i < 3; i++ {
  2189. rr := request(t, s, "PUT", "/subscriber1topic", "some message", nil)
  2190. require.Equal(t, 200, rr.Code)
  2191. }
  2192. rr = request(t, s, "PUT", "/subscriber1topic", "some message", nil)
  2193. require.Equal(t, 429, rr.Code)
  2194. rr = request(t, s, "PUT", "/up012345678912", "some message", nil)
  2195. require.Equal(t, 429, rr.Code)
  2196. }
  2197. func TestServer_SubscriberRateLimiting_UP_Only(t *testing.T) {
  2198. c := newTestConfigWithAuthFile(t)
  2199. c.VisitorRequestLimitBurst = 3
  2200. c.VisitorSubscriberRateLimiting = true
  2201. s := newTestServer(t, c)
  2202. // "Register" 5 different UnifiedPush visitors
  2203. for i := 0; i < 5; i++ {
  2204. subscriberFn := func(r *http.Request) {
  2205. r.RemoteAddr = fmt.Sprintf("1.2.3.%d:1234", i+1)
  2206. }
  2207. rr := request(t, s, "GET", fmt.Sprintf("/up12345678901%d/json?poll=1", i), "", nil, subscriberFn)
  2208. require.Equal(t, 200, rr.Code)
  2209. }
  2210. // Publish 2 messages per topic
  2211. for i := 0; i < 5; i++ {
  2212. for j := 0; j < 2; j++ {
  2213. rr := request(t, s, "PUT", fmt.Sprintf("/up12345678901%d?up=1", i), "some message", nil)
  2214. require.Equal(t, 200, rr.Code)
  2215. }
  2216. }
  2217. }
  2218. func TestServer_Matrix_SubscriberRateLimiting_UP_Only(t *testing.T) {
  2219. c := newTestConfig(t)
  2220. c.VisitorRequestLimitBurst = 3
  2221. c.VisitorSubscriberRateLimiting = true
  2222. s := newTestServer(t, c)
  2223. // "Register" 5 different UnifiedPush visitors
  2224. for i := 0; i < 5; i++ {
  2225. rr := request(t, s, "GET", fmt.Sprintf("/up12345678901%d/json?poll=1", i), "", nil, func(r *http.Request) {
  2226. r.RemoteAddr = fmt.Sprintf("1.2.3.%d:1234", i+1)
  2227. })
  2228. require.Equal(t, 200, rr.Code)
  2229. }
  2230. // Publish 2 messages per topic
  2231. for i := 0; i < 5; i++ {
  2232. notification := fmt.Sprintf(`{"notification":{"devices":[{"pushkey":"http://127.0.0.1:12345/up12345678901%d?up=1"}]}}`, i)
  2233. for j := 0; j < 2; j++ {
  2234. response := request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  2235. require.Equal(t, 200, response.Code)
  2236. require.Equal(t, `{"rejected":[]}`+"\n", response.Body.String())
  2237. }
  2238. response := request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  2239. require.Equal(t, 429, response.Code, notification)
  2240. require.Equal(t, 42901, toHTTPError(t, response.Body.String()).Code)
  2241. }
  2242. }
  2243. func TestServer_SubscriberRateLimiting_VisitorExpiration(t *testing.T) {
  2244. c := newTestConfig(t)
  2245. c.VisitorRequestLimitBurst = 3
  2246. c.VisitorSubscriberRateLimiting = true
  2247. s := newTestServer(t, c)
  2248. // "Register" rate visitor
  2249. subscriberFn := func(r *http.Request) {
  2250. r.RemoteAddr = "1.2.3.4:1234"
  2251. }
  2252. rr := request(t, s, "GET", "/upAAAAAAAAAAAA/json?poll=1", "", nil, subscriberFn)
  2253. require.Equal(t, 200, rr.Code)
  2254. require.Equal(t, "1.2.3.4", s.topics["upAAAAAAAAAAAA"].rateVisitor.ip.String())
  2255. require.Equal(t, s.visitors["ip:1.2.3.4"], s.topics["upAAAAAAAAAAAA"].rateVisitor)
  2256. // Publish message, observe rate visitor tokens being decreased
  2257. response := request(t, s, "POST", "/upAAAAAAAAAAAA", "some message", nil)
  2258. require.Equal(t, 200, response.Code)
  2259. require.Equal(t, int64(0), s.visitors["ip:9.9.9.9"].messagesLimiter.Value())
  2260. require.Equal(t, int64(1), s.topics["upAAAAAAAAAAAA"].rateVisitor.messagesLimiter.Value())
  2261. require.Equal(t, s.visitors["ip:1.2.3.4"], s.topics["upAAAAAAAAAAAA"].rateVisitor)
  2262. // Expire visitor
  2263. s.visitors["ip:1.2.3.4"].seen = time.Now().Add(-1 * 25 * time.Hour)
  2264. s.pruneVisitors()
  2265. // Publish message again, observe that rateVisitor is not used anymore and is reset
  2266. response = request(t, s, "POST", "/upAAAAAAAAAAAA", "some message", nil)
  2267. require.Equal(t, 200, response.Code)
  2268. require.Equal(t, int64(1), s.visitors["ip:9.9.9.9"].messagesLimiter.Value())
  2269. require.Nil(t, s.topics["upAAAAAAAAAAAA"].rateVisitor)
  2270. require.Nil(t, s.visitors["ip:1.2.3.4"])
  2271. }
  2272. func TestServer_SubscriberRateLimiting_ProtectedTopics_WithDefaultReadWrite(t *testing.T) {
  2273. c := newTestConfigWithAuthFile(t)
  2274. c.AuthDefault = user.PermissionReadWrite
  2275. c.VisitorSubscriberRateLimiting = true
  2276. s := newTestServer(t, c)
  2277. // Create some ACLs
  2278. require.Nil(t, s.userManager.AllowAccess(user.Everyone, "announcements", user.PermissionRead))
  2279. // Set rate visitor as ip:1.2.3.4 on topic
  2280. // - "up123456789012": Allowed, because no ACLs and nobody owns the topic
  2281. // - "announcements": NOT allowed, because it has read-only permissions for everyone
  2282. rr := request(t, s, "GET", "/up123456789012,announcements/json?poll=1", "", nil, func(r *http.Request) {
  2283. r.RemoteAddr = "1.2.3.4:1234"
  2284. })
  2285. require.Equal(t, 200, rr.Code)
  2286. require.Equal(t, "1.2.3.4", s.topics["up123456789012"].rateVisitor.ip.String())
  2287. require.Nil(t, s.topics["announcements"].rateVisitor)
  2288. }
  2289. func TestServer_MessageHistoryAndStatsEndpoint(t *testing.T) {
  2290. c := newTestConfig(t)
  2291. c.ManagerInterval = 2 * time.Second
  2292. s := newTestServer(t, c)
  2293. // Publish some messages, and get stats
  2294. for i := 0; i < 5; i++ {
  2295. response := request(t, s, "POST", "/mytopic", "some message", nil)
  2296. require.Equal(t, 200, response.Code)
  2297. }
  2298. require.Equal(t, int64(5), s.messages)
  2299. require.Equal(t, []int64{0}, s.messagesHistory)
  2300. response := request(t, s, "GET", "/v1/stats", "", nil)
  2301. require.Equal(t, 200, response.Code)
  2302. require.Equal(t, `{"messages":5,"messages_rate":0}`+"\n", response.Body.String())
  2303. // Run manager and see message history update
  2304. s.execManager()
  2305. require.Equal(t, []int64{0, 5}, s.messagesHistory)
  2306. response = request(t, s, "GET", "/v1/stats", "", nil)
  2307. require.Equal(t, 200, response.Code)
  2308. require.Equal(t, `{"messages":5,"messages_rate":2.5}`+"\n", response.Body.String()) // 5 messages in 2 seconds = 2.5 messages per second
  2309. // Publish some more messages
  2310. for i := 0; i < 10; i++ {
  2311. response := request(t, s, "POST", "/mytopic", "some message", nil)
  2312. require.Equal(t, 200, response.Code)
  2313. }
  2314. require.Equal(t, int64(15), s.messages)
  2315. require.Equal(t, []int64{0, 5}, s.messagesHistory)
  2316. response = request(t, s, "GET", "/v1/stats", "", nil)
  2317. require.Equal(t, 200, response.Code)
  2318. require.Equal(t, `{"messages":15,"messages_rate":2.5}`+"\n", response.Body.String()) // Rate did not update yet
  2319. // Run manager and see message history update
  2320. s.execManager()
  2321. require.Equal(t, []int64{0, 5, 15}, s.messagesHistory)
  2322. response = request(t, s, "GET", "/v1/stats", "", nil)
  2323. require.Equal(t, 200, response.Code)
  2324. require.Equal(t, `{"messages":15,"messages_rate":3.75}`+"\n", response.Body.String()) // 15 messages in 4 seconds = 3.75 messages per second
  2325. }
  2326. func TestServer_MessageHistoryMaxSize(t *testing.T) {
  2327. t.Parallel()
  2328. s := newTestServer(t, newTestConfig(t))
  2329. for i := 0; i < 20; i++ {
  2330. s.messages = int64(i)
  2331. s.execManager()
  2332. }
  2333. require.Equal(t, []int64{10, 11, 12, 13, 14, 15, 16, 17, 18, 19}, s.messagesHistory)
  2334. }
  2335. func TestServer_MessageCountPersistence(t *testing.T) {
  2336. t.Parallel()
  2337. c := newTestConfig(t)
  2338. s := newTestServer(t, c)
  2339. s.messages = 1234
  2340. s.execManager()
  2341. waitFor(t, func() bool {
  2342. messages, err := s.messageCache.Stats()
  2343. require.Nil(t, err)
  2344. return messages == 1234
  2345. })
  2346. s = newTestServer(t, c)
  2347. require.Equal(t, int64(1234), s.messages)
  2348. }
  2349. func TestServer_PublishWithUTF8MimeHeader(t *testing.T) {
  2350. t.Parallel()
  2351. s := newTestServer(t, newTestConfig(t))
  2352. response := request(t, s, "POST", "/mytopic", "some attachment", map[string]string{
  2353. "X-Filename": "some =?UTF-8?q?=C3=A4?=ttachment.txt",
  2354. "X-Message": "=?UTF-8?B?8J+HqfCfh6o=?=",
  2355. "X-Title": "=?UTF-8?B?bnRmeSDlvojmo5I=?=, no really I mean it! =?UTF-8?Q?This is q=C3=BC=C3=B6ted-print=C3=A4ble.?=",
  2356. "X-Tags": "=?UTF-8?B?8J+HqfCfh6o=?=, =?UTF-8?B?bnRmeSDlvojmo5I=?=",
  2357. "X-Click": "=?uTf-8?b?aHR0cHM6Ly/wn5KpLmxh?=",
  2358. "X-Actions": "http, \"=?utf-8?q?Mettre =C3=A0 jour?=\", \"https://my.tld/webhook/netbird-update\"; =?utf-8?b?aHR0cCwg6L+Z5piv5LiA5Liq5qCH562+LCBodHRwczovL/CfkqkubGE=?=",
  2359. })
  2360. require.Equal(t, 200, response.Code)
  2361. m := toMessage(t, response.Body.String())
  2362. require.Equal(t, "🇩🇪", m.Message)
  2363. require.Equal(t, "ntfy 很棒, no really I mean it! This is qüöted-printäble.", m.Title)
  2364. require.Equal(t, "some ättachment.txt", m.Attachment.Name)
  2365. require.Equal(t, "🇩🇪", m.Tags[0])
  2366. require.Equal(t, "ntfy 很棒", m.Tags[1])
  2367. require.Equal(t, "https://💩.la", m.Click)
  2368. require.Equal(t, "Mettre à jour", m.Actions[0].Label)
  2369. require.Equal(t, "http", m.Actions[1].Action)
  2370. require.Equal(t, "这是一个标签", m.Actions[1].Label)
  2371. require.Equal(t, "https://💩.la", m.Actions[1].URL)
  2372. }
  2373. func TestServer_UpstreamBaseURL_Success(t *testing.T) {
  2374. t.Parallel()
  2375. var pollID atomic.Pointer[string]
  2376. upstreamServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  2377. body, err := io.ReadAll(r.Body)
  2378. require.Nil(t, err)
  2379. require.Equal(t, "/87c9cddf7b0105f5fe849bf084c6e600be0fde99be3223335199b4965bd7b735", r.URL.Path)
  2380. require.Equal(t, "", string(body))
  2381. require.NotEmpty(t, r.Header.Get("X-Poll-ID"))
  2382. pollID.Store(util.String(r.Header.Get("X-Poll-ID")))
  2383. }))
  2384. defer upstreamServer.Close()
  2385. c := newTestConfigWithAuthFile(t)
  2386. c.BaseURL = "http://myserver.internal"
  2387. c.UpstreamBaseURL = upstreamServer.URL
  2388. s := newTestServer(t, c)
  2389. // Send message, and wait for upstream server to receive it
  2390. response := request(t, s, "PUT", "/mytopic", `hi there`, nil)
  2391. require.Equal(t, 200, response.Code)
  2392. m := toMessage(t, response.Body.String())
  2393. require.NotEmpty(t, m.ID)
  2394. require.Equal(t, "hi there", m.Message)
  2395. waitFor(t, func() bool {
  2396. pID := pollID.Load()
  2397. return pID != nil && *pID == m.ID
  2398. })
  2399. }
  2400. func TestServer_UpstreamBaseURL_With_Access_Token_Success(t *testing.T) {
  2401. t.Parallel()
  2402. var pollID atomic.Pointer[string]
  2403. upstreamServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  2404. body, err := io.ReadAll(r.Body)
  2405. require.Nil(t, err)
  2406. require.Equal(t, "/a1c72bcb4daf5af54d13ef86aea8f76c11e8b88320d55f1811d5d7b173bcc1df", r.URL.Path)
  2407. require.Equal(t, "Bearer tk_1234567890", r.Header.Get("Authorization"))
  2408. require.Equal(t, "", string(body))
  2409. require.NotEmpty(t, r.Header.Get("X-Poll-ID"))
  2410. pollID.Store(util.String(r.Header.Get("X-Poll-ID")))
  2411. }))
  2412. defer upstreamServer.Close()
  2413. c := newTestConfigWithAuthFile(t)
  2414. c.BaseURL = "http://myserver.internal"
  2415. c.UpstreamBaseURL = upstreamServer.URL
  2416. c.UpstreamAccessToken = "tk_1234567890"
  2417. s := newTestServer(t, c)
  2418. // Send message, and wait for upstream server to receive it
  2419. response := request(t, s, "PUT", "/mytopic1", `hi there`, nil)
  2420. require.Equal(t, 200, response.Code)
  2421. m := toMessage(t, response.Body.String())
  2422. require.NotEmpty(t, m.ID)
  2423. require.Equal(t, "hi there", m.Message)
  2424. waitFor(t, func() bool {
  2425. pID := pollID.Load()
  2426. return pID != nil && *pID == m.ID
  2427. })
  2428. }
  2429. func TestServer_UpstreamBaseURL_DoNotForwardUnifiedPush(t *testing.T) {
  2430. t.Parallel()
  2431. upstreamServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  2432. t.Fatal("UnifiedPush messages should not be forwarded")
  2433. }))
  2434. defer upstreamServer.Close()
  2435. c := newTestConfigWithAuthFile(t)
  2436. c.BaseURL = "http://myserver.internal"
  2437. c.UpstreamBaseURL = upstreamServer.URL
  2438. s := newTestServer(t, c)
  2439. // Send UP message, this should not forward to upstream server
  2440. response := request(t, s, "PUT", "/mytopic?up=1", `hi there`, nil)
  2441. require.Equal(t, 200, response.Code)
  2442. m := toMessage(t, response.Body.String())
  2443. require.NotEmpty(t, m.ID)
  2444. require.Equal(t, "hi there", m.Message)
  2445. // Forwarding is done asynchronously, so wait a bit.
  2446. // This ensures that the t.Fatal above is actually not triggered.
  2447. time.Sleep(500 * time.Millisecond)
  2448. }
  2449. func TestServer_MessageTemplate(t *testing.T) {
  2450. t.Parallel()
  2451. s := newTestServer(t, newTestConfig(t))
  2452. response := request(t, s, "PUT", "/mytopic", `{"foo":"bar", "nested":{"title":"here"}}`, map[string]string{
  2453. "X-Message": "{{.foo}}",
  2454. "X-Title": "{{.nested.title}}",
  2455. "X-Template": "1",
  2456. })
  2457. require.Equal(t, 200, response.Code)
  2458. m := toMessage(t, response.Body.String())
  2459. require.Equal(t, "bar", m.Message)
  2460. require.Equal(t, "here", m.Title)
  2461. }
  2462. func TestServer_MessageTemplate_RepeatPlaceholder(t *testing.T) {
  2463. t.Parallel()
  2464. s := newTestServer(t, newTestConfig(t))
  2465. response := request(t, s, "PUT", "/mytopic", `{"foo":"bar", "nested":{"title":"here"}}`, map[string]string{
  2466. "Message": "{{.foo}} is {{.foo}}",
  2467. "Title": "{{.nested.title}} is {{.nested.title}}",
  2468. "Template": "1",
  2469. })
  2470. require.Equal(t, 200, response.Code)
  2471. m := toMessage(t, response.Body.String())
  2472. require.Equal(t, "bar is bar", m.Message)
  2473. require.Equal(t, "here is here", m.Title)
  2474. }
  2475. func TestServer_MessageTemplate_JSONBody(t *testing.T) {
  2476. t.Parallel()
  2477. s := newTestServer(t, newTestConfig(t))
  2478. body := `{"topic": "mytopic", "message": "{\"foo\":\"bar\",\"nested\":{\"title\":\"here\"}}"}`
  2479. response := request(t, s, "PUT", "/", body, map[string]string{
  2480. "m": "{{.foo}}",
  2481. "t": "{{.nested.title}}",
  2482. "tpl": "1",
  2483. })
  2484. require.Equal(t, 200, response.Code)
  2485. m := toMessage(t, response.Body.String())
  2486. require.Equal(t, "bar", m.Message)
  2487. require.Equal(t, "here", m.Title)
  2488. }
  2489. func TestServer_MessageTemplate_MalformedJSONBody(t *testing.T) {
  2490. t.Parallel()
  2491. s := newTestServer(t, newTestConfig(t))
  2492. body := `{"topic": "mytopic", "message": "{\"foo\":\"bar\",\"nested\":{\"title\":\"here\"INVALID"}`
  2493. response := request(t, s, "PUT", "/", body, map[string]string{
  2494. "X-Message": "{{.foo}}",
  2495. "X-Title": "{{.nested.title}}",
  2496. "X-Template": "1",
  2497. })
  2498. require.Equal(t, 400, response.Code)
  2499. require.Equal(t, 40042, toHTTPError(t, response.Body.String()).Code)
  2500. }
  2501. func TestServer_MessageTemplate_PlaceholderTypo(t *testing.T) {
  2502. t.Parallel()
  2503. s := newTestServer(t, newTestConfig(t))
  2504. response := request(t, s, "PUT", "/mytopic", `{"foo":"bar", "nested":{"title":"here"}}`, map[string]string{
  2505. "X-Message": "{{.food}}",
  2506. "X-Title": "{{.neste.title}}",
  2507. "X-Template": "1",
  2508. })
  2509. require.Equal(t, 200, response.Code)
  2510. m := toMessage(t, response.Body.String())
  2511. require.Equal(t, "<no value>", m.Message)
  2512. require.Equal(t, "<no value>", m.Title)
  2513. }
  2514. func TestServer_MessageTemplate_MultiplePlaceholders(t *testing.T) {
  2515. t.Parallel()
  2516. s := newTestServer(t, newTestConfig(t))
  2517. response := request(t, s, "PUT", "/mytopic", `{"foo":"bar", "nested":{"title":"here"}}`, map[string]string{
  2518. "X-Message": "{{.foo}} is {{.nested.title}}",
  2519. "X-Template": "1",
  2520. })
  2521. require.Equal(t, 200, response.Code)
  2522. m := toMessage(t, response.Body.String())
  2523. require.Equal(t, "bar is here", m.Message)
  2524. }
  2525. func TestServer_MessageTemplate_Range(t *testing.T) {
  2526. t.Parallel()
  2527. s := newTestServer(t, newTestConfig(t))
  2528. jsonBody := `{"foo": "bar", "errors": [{"level": "severe", "url": "https://severe1.com"},{"level": "warning", "url": "https://warning.com"},{"level": "severe", "url": "https://severe2.com"}]}`
  2529. response := request(t, s, "PUT", "/mytopic", jsonBody, map[string]string{
  2530. "X-Message": `Severe URLs:\n{{range .errors}}{{if eq .level "severe"}}- {{.url}}\n{{end}}{{end}}`,
  2531. "X-Template": "1",
  2532. })
  2533. require.Equal(t, 200, response.Code)
  2534. m := toMessage(t, response.Body.String())
  2535. require.Equal(t, "Severe URLs:\n- https://severe1.com\n- https://severe2.com", m.Message)
  2536. }
  2537. func TestServer_MessageTemplate_ExceedMessageSize_TemplatedMessageOK(t *testing.T) {
  2538. t.Parallel()
  2539. c := newTestConfig(t)
  2540. c.MessageSizeLimit = 25 // 25 < len(HTTP body) < 32k, and len(m.Message) < 25
  2541. s := newTestServer(t, c)
  2542. response := request(t, s, "PUT", "/mytopic", `{"foo":"bar", "nested":{"title":"here"}}`, map[string]string{
  2543. "X-Message": "{{.foo}}",
  2544. "X-Title": "{{.nested.title}}",
  2545. "X-Template": "yes",
  2546. })
  2547. require.Equal(t, 200, response.Code)
  2548. m := toMessage(t, response.Body.String())
  2549. require.Equal(t, "bar", m.Message)
  2550. require.Equal(t, "here", m.Title)
  2551. }
  2552. func TestServer_MessageTemplate_ExceedMessageSize_TemplatedMessageTooLong(t *testing.T) {
  2553. t.Parallel()
  2554. c := newTestConfig(t)
  2555. c.MessageSizeLimit = 21 // 21 < len(HTTP body) < 32k, but !len(m.Message) < 21
  2556. s := newTestServer(t, c)
  2557. response := request(t, s, "PUT", "/mytopic", `{"foo":"This is a long message"}`, map[string]string{
  2558. "X-Message": "{{.foo}}",
  2559. "X-Template": "1",
  2560. })
  2561. require.Equal(t, 400, response.Code)
  2562. require.Equal(t, 40041, toHTTPError(t, response.Body.String()).Code)
  2563. }
  2564. func TestServer_MessageTemplate_Grafana(t *testing.T) {
  2565. t.Parallel()
  2566. s := newTestServer(t, newTestConfig(t))
  2567. body := `{"receiver":"ntfy\\.example\\.com/alerts","status":"resolved","alerts":[{"status":"resolved","labels":{"alertname":"Load avg 15m too high","grafana_folder":"Node alerts","instance":"10.108.0.2:9100","job":"node-exporter"},"annotations":{"summary":"15m load average too high"},"startsAt":"2024-03-15T02:28:00Z","endsAt":"2024-03-15T02:42:00Z","generatorURL":"localhost:3000/alerting/grafana/NW9oDw-4z/view","fingerprint":"becbfb94bd81ef48","silenceURL":"localhost:3000/alerting/silence/new?alertmanager=grafana&matcher=alertname%3DLoad+avg+15m+too+high&matcher=grafana_folder%3DNode+alerts&matcher=instance%3D10.108.0.2%3A9100&matcher=job%3Dnode-exporter","dashboardURL":"","panelURL":"","values":{"B":18.98211314475876,"C":0},"valueString":"[ var='B' labels={__name__=node_load15, instance=10.108.0.2:9100, job=node-exporter} value=18.98211314475876 ], [ var='C' labels={__name__=node_load15, instance=10.108.0.2:9100, job=node-exporter} value=0 ]"}],"groupLabels":{"alertname":"Load avg 15m too high","grafana_folder":"Node alerts"},"commonLabels":{"alertname":"Load avg 15m too high","grafana_folder":"Node alerts","instance":"10.108.0.2:9100","job":"node-exporter"},"commonAnnotations":{"summary":"15m load average too high"},"externalURL":"localhost:3000/","version":"1","groupKey":"{}:{alertname=\"Load avg 15m too high\", grafana_folder=\"Node alerts\"}","truncatedAlerts":0,"orgId":1,"title":"[RESOLVED] Load avg 15m too high Node alerts (10.108.0.2:9100 node-exporter)","state":"ok","message":"**Resolved**\n\nValue: B=18.98211314475876, C=0\nLabels:\n - alertname = Load avg 15m too high\n - grafana_folder = Node alerts\n - instance = 10.108.0.2:9100\n - job = node-exporter\nAnnotations:\n - summary = 15m load average too high\nSource: localhost:3000/alerting/grafana/NW9oDw-4z/view\nSilence: localhost:3000/alerting/silence/new?alertmanager=grafana&matcher=alertname%3DLoad+avg+15m+too+high&matcher=grafana_folder%3DNode+alerts&matcher=instance%3D10.108.0.2%3A9100&matcher=job%3Dnode-exporter\n"}`
  2568. response := request(t, s, "PUT", "/mytopic?tpl=yes&title=Grafana+alert:+{{.title}}&message={{.message}}", body, nil)
  2569. require.Equal(t, 200, response.Code)
  2570. m := toMessage(t, response.Body.String())
  2571. require.Equal(t, "Grafana alert: [RESOLVED] Load avg 15m too high Node alerts (10.108.0.2:9100 node-exporter)", m.Title)
  2572. require.Equal(t, `**Resolved**
  2573. Value: B=18.98211314475876, C=0
  2574. Labels:
  2575. - alertname = Load avg 15m too high
  2576. - grafana_folder = Node alerts
  2577. - instance = 10.108.0.2:9100
  2578. - job = node-exporter
  2579. Annotations:
  2580. - summary = 15m load average too high
  2581. Source: localhost:3000/alerting/grafana/NW9oDw-4z/view
  2582. Silence: localhost:3000/alerting/silence/new?alertmanager=grafana&matcher=alertname%3DLoad+avg+15m+too+high&matcher=grafana_folder%3DNode+alerts&matcher=instance%3D10.108.0.2%3A9100&matcher=job%3Dnode-exporter`, m.Message)
  2583. }
  2584. func TestServer_MessageTemplate_GitHub(t *testing.T) {
  2585. t.Parallel()
  2586. s := newTestServer(t, newTestConfig(t))
  2587. body := `{"action":"opened","number":1,"pull_request":{"url":"https://api.github.com/repos/binwiederhier/dabble/pulls/1","id":1783420972,"node_id":"PR_kwDOHAbdo85qTNgs","html_url":"https://github.com/binwiederhier/dabble/pull/1","diff_url":"https://github.com/binwiederhier/dabble/pull/1.diff","patch_url":"https://github.com/binwiederhier/dabble/pull/1.patch","issue_url":"https://api.github.com/repos/binwiederhier/dabble/issues/1","number":1,"state":"open","locked":false,"title":"A sample PR from Phil","user":{"login":"binwiederhier","id":664597,"node_id":"MDQ6VXNlcjY2NDU5Nw==","avatar_url":"https://avatars.githubusercontent.com/u/664597?v=4","gravatar_id":"","url":"https://api.github.com/users/binwiederhier","html_url":"https://github.com/binwiederhier","followers_url":"https://api.github.com/users/binwiederhier/followers","following_url":"https://api.github.com/users/binwiederhier/following{/other_user}","gists_url":"https://api.github.com/users/binwiederhier/gists{/gist_id}","starred_url":"https://api.github.com/users/binwiederhier/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/binwiederhier/subscriptions","organizations_url":"https://api.github.com/users/binwiederhier/orgs","repos_url":"https://api.github.com/users/binwiederhier/repos","events_url":"https://api.github.com/users/binwiederhier/events{/privacy}","received_events_url":"https://api.github.com/users/binwiederhier/received_events","type":"User","site_admin":false},"body":null,"created_at":"2024-03-21T02:52:09Z","updated_at":"2024-03-21T02:52:09Z","closed_at":null,"merged_at":null,"merge_commit_sha":null,"assignee":null,"assignees":[],"requested_reviewers":[],"requested_teams":[],"labels":[],"milestone":null,"draft":false,"commits_url":"https://api.github.com/repos/binwiederhier/dabble/pulls/1/commits","review_comments_url":"https://api.github.com/repos/binwiederhier/dabble/pulls/1/comments","review_comment_url":"https://api.github.com/repos/binwiederhier/dabble/pulls/comments{/number}","comments_url":"https://api.github.com/repos/binwiederhier/dabble/issues/1/comments","statuses_url":"https://api.github.com/repos/binwiederhier/dabble/statuses/5703842cc5715ed1e358d23ebb693db09747ae9b","head":{"label":"binwiederhier:aa","ref":"aa","sha":"5703842cc5715ed1e358d23ebb693db09747ae9b","user":{"login":"binwiederhier","id":664597,"node_id":"MDQ6VXNlcjY2NDU5Nw==","avatar_url":"https://avatars.githubusercontent.com/u/664597?v=4","gravatar_id":"","url":"https://api.github.com/users/binwiederhier","html_url":"https://github.com/binwiederhier","followers_url":"https://api.github.com/users/binwiederhier/followers","following_url":"https://api.github.com/users/binwiederhier/following{/other_user}","gists_url":"https://api.github.com/users/binwiederhier/gists{/gist_id}","starred_url":"https://api.github.com/users/binwiederhier/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/binwiederhier/subscriptions","organizations_url":"https://api.github.com/users/binwiederhier/orgs","repos_url":"https://api.github.com/users/binwiederhier/repos","events_url":"https://api.github.com/users/binwiederhier/events{/privacy}","received_events_url":"https://api.github.com/users/binwiederhier/received_events","type":"User","site_admin":false},"repo":{"id":470212003,"node_id":"R_kgDOHAbdow","name":"dabble","full_name":"binwiederhier/dabble","private":false,"owner":{"login":"binwiederhier","id":664597,"node_id":"MDQ6VXNlcjY2NDU5Nw==","avatar_url":"https://avatars.githubusercontent.com/u/664597?v=4","gravatar_id":"","url":"https://api.github.com/users/binwiederhier","html_url":"https://github.com/binwiederhier","followers_url":"https://api.github.com/users/binwiederhier/followers","following_url":"https://api.github.com/users/binwiederhier/following{/other_user}","gists_url":"https://api.github.com/users/binwiederhier/gists{/gist_id}","starred_url":"https://api.github.com/users/binwiederhier/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/binwiederhier/subscriptions","organizations_url":"https://api.github.com/users/binwiederhier/orgs","repos_url":"https://api.github.com/users/binwiederhier/repos","events_url":"https://api.github.com/users/binwiederhier/events{/privacy}","received_events_url":"https://api.github.com/users/binwiederhier/received_events","type":"User","site_admin":false},"html_url":"https://github.com/binwiederhier/dabble","description":"A repo for dabbling","fork":false,"url":"https://api.github.com/repos/binwiederhier/dabble","forks_url":"https://api.github.com/repos/binwiederhier/dabble/forks","keys_url":"https://api.github.com/repos/binwiederhier/dabble/keys{/key_id}","collaborators_url":"https://api.github.com/repos/binwiederhier/dabble/collaborators{/collaborator}","teams_url":"https://api.github.com/repos/binwiederhier/dabble/teams","hooks_url":"https://api.github.com/repos/binwiederhier/dabble/hooks","issue_events_url":"https://api.github.com/repos/binwiederhier/dabble/issues/events{/number}","events_url":"https://api.github.com/repos/binwiederhier/dabble/events","assignees_url":"https://api.github.com/repos/binwiederhier/dabble/assignees{/user}","branches_url":"https://api.github.com/repos/binwiederhier/dabble/branches{/branch}","tags_url":"https://api.github.com/repos/binwiederhier/dabble/tags","blobs_url":"https://api.github.com/repos/binwiederhier/dabble/git/blobs{/sha}","git_tags_url":"https://api.github.com/repos/binwiederhier/dabble/git/tags{/sha}","git_refs_url":"https://api.github.com/repos/binwiederhier/dabble/git/refs{/sha}","trees_url":"https://api.github.com/repos/binwiederhier/dabble/git/trees{/sha}","statuses_url":"https://api.github.com/repos/binwiederhier/dabble/statuses/{sha}","languages_url":"https://api.github.com/repos/binwiederhier/dabble/languages","stargazers_url":"https://api.github.com/repos/binwiederhier/dabble/stargazers","contributors_url":"https://api.github.com/repos/binwiederhier/dabble/contributors","subscribers_url":"https://api.github.com/repos/binwiederhier/dabble/subscribers","subscription_url":"https://api.github.com/repos/binwiederhier/dabble/subscription","commits_url":"https://api.github.com/repos/binwiederhier/dabble/commits{/sha}","git_commits_url":"https://api.github.com/repos/binwiederhier/dabble/git/commits{/sha}","comments_url":"https://api.github.com/repos/binwiederhier/dabble/comments{/number}","issue_comment_url":"https://api.github.com/repos/binwiederhier/dabble/issues/comments{/number}","contents_url":"https://api.github.com/repos/binwiederhier/dabble/contents/{+path}","compare_url":"https://api.github.com/repos/binwiederhier/dabble/compare/{base}...{head}","merges_url":"https://api.github.com/repos/binwiederhier/dabble/merges","archive_url":"https://api.github.com/repos/binwiederhier/dabble/{archive_format}{/ref}","downloads_url":"https://api.github.com/repos/binwiederhier/dabble/downloads","issues_url":"https://api.github.com/repos/binwiederhier/dabble/issues{/number}","pulls_url":"https://api.github.com/repos/binwiederhier/dabble/pulls{/number}","milestones_url":"https://api.github.com/repos/binwiederhier/dabble/milestones{/number}","notifications_url":"https://api.github.com/repos/binwiederhier/dabble/notifications{?since,all,participating}","labels_url":"https://api.github.com/repos/binwiederhier/dabble/labels{/name}","releases_url":"https://api.github.com/repos/binwiederhier/dabble/releases{/id}","deployments_url":"https://api.github.com/repos/binwiederhier/dabble/deployments","created_at":"2022-03-15T15:06:17Z","updated_at":"2022-03-15T15:06:17Z","pushed_at":"2024-03-21T02:52:10Z","git_url":"git://github.com/binwiederhier/dabble.git","ssh_url":"git@github.com:binwiederhier/dabble.git","clone_url":"https://github.com/binwiederhier/dabble.git","svn_url":"https://github.com/binwiederhier/dabble","homepage":null,"size":1,"stargazers_count":0,"watchers_count":0,"language":null,"has_issues":true,"has_projects":true,"has_downloads":true,"has_wiki":true,"has_pages":false,"has_discussions":false,"forks_count":0,"mirror_url":null,"archived":false,"disabled":false,"open_issues_count":1,"license":null,"allow_forking":true,"is_template":false,"web_commit_signoff_required":false,"topics":[],"visibility":"public","forks":0,"open_issues":1,"watchers":0,"default_branch":"main","allow_squash_merge":true,"allow_merge_commit":true,"allow_rebase_merge":true,"allow_auto_merge":false,"delete_branch_on_merge":false,"allow_update_branch":false,"use_squash_pr_title_as_default":false,"squash_merge_commit_message":"COMMIT_MESSAGES","squash_merge_commit_title":"COMMIT_OR_PR_TITLE","merge_commit_message":"PR_TITLE","merge_commit_title":"MERGE_MESSAGE"}},"base":{"label":"binwiederhier:main","ref":"main","sha":"72d931a20bb83d123ab45accaf761150c8b01211","user":{"login":"binwiederhier","id":664597,"node_id":"MDQ6VXNlcjY2NDU5Nw==","avatar_url":"https://avatars.githubusercontent.com/u/664597?v=4","gravatar_id":"","url":"https://api.github.com/users/binwiederhier","html_url":"https://github.com/binwiederhier","followers_url":"https://api.github.com/users/binwiederhier/followers","following_url":"https://api.github.com/users/binwiederhier/following{/other_user}","gists_url":"https://api.github.com/users/binwiederhier/gists{/gist_id}","starred_url":"https://api.github.com/users/binwiederhier/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/binwiederhier/subscriptions","organizations_url":"https://api.github.com/users/binwiederhier/orgs","repos_url":"https://api.github.com/users/binwiederhier/repos","events_url":"https://api.github.com/users/binwiederhier/events{/privacy}","received_events_url":"https://api.github.com/users/binwiederhier/received_events","type":"User","site_admin":false},"repo":{"id":470212003,"node_id":"R_kgDOHAbdow","name":"dabble","full_name":"binwiederhier/dabble","private":false,"owner":{"login":"binwiederhier","id":664597,"node_id":"MDQ6VXNlcjY2NDU5Nw==","avatar_url":"https://avatars.githubusercontent.com/u/664597?v=4","gravatar_id":"","url":"https://api.github.com/users/binwiederhier","html_url":"https://github.com/binwiederhier","followers_url":"https://api.github.com/users/binwiederhier/followers","following_url":"https://api.github.com/users/binwiederhier/following{/other_user}","gists_url":"https://api.github.com/users/binwiederhier/gists{/gist_id}","starred_url":"https://api.github.com/users/binwiederhier/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/binwiederhier/subscriptions","organizations_url":"https://api.github.com/users/binwiederhier/orgs","repos_url":"https://api.github.com/users/binwiederhier/repos","events_url":"https://api.github.com/users/binwiederhier/events{/privacy}","received_events_url":"https://api.github.com/users/binwiederhier/received_events","type":"User","site_admin":false},"html_url":"https://github.com/binwiederhier/dabble","description":"A repo for dabbling","fork":false,"url":"https://api.github.com/repos/binwiederhier/dabble","forks_url":"https://api.github.com/repos/binwiederhier/dabble/forks","keys_url":"https://api.github.com/repos/binwiederhier/dabble/keys{/key_id}","collaborators_url":"https://api.github.com/repos/binwiederhier/dabble/collaborators{/collaborator}","teams_url":"https://api.github.com/repos/binwiederhier/dabble/teams","hooks_url":"https://api.github.com/repos/binwiederhier/dabble/hooks","issue_events_url":"https://api.github.com/repos/binwiederhier/dabble/issues/events{/number}","events_url":"https://api.github.com/repos/binwiederhier/dabble/events","assignees_url":"https://api.github.com/repos/binwiederhier/dabble/assignees{/user}","branches_url":"https://api.github.com/repos/binwiederhier/dabble/branches{/branch}","tags_url":"https://api.github.com/repos/binwiederhier/dabble/tags","blobs_url":"https://api.github.com/repos/binwiederhier/dabble/git/blobs{/sha}","git_tags_url":"https://api.github.com/repos/binwiederhier/dabble/git/tags{/sha}","git_refs_url":"https://api.github.com/repos/binwiederhier/dabble/git/refs{/sha}","trees_url":"https://api.github.com/repos/binwiederhier/dabble/git/trees{/sha}","statuses_url":"https://api.github.com/repos/binwiederhier/dabble/statuses/{sha}","languages_url":"https://api.github.com/repos/binwiederhier/dabble/languages","stargazers_url":"https://api.github.com/repos/binwiederhier/dabble/stargazers","contributors_url":"https://api.github.com/repos/binwiederhier/dabble/contributors","subscribers_url":"https://api.github.com/repos/binwiederhier/dabble/subscribers","subscription_url":"https://api.github.com/repos/binwiederhier/dabble/subscription","commits_url":"https://api.github.com/repos/binwiederhier/dabble/commits{/sha}","git_commits_url":"https://api.github.com/repos/binwiederhier/dabble/git/commits{/sha}","comments_url":"https://api.github.com/repos/binwiederhier/dabble/comments{/number}","issue_comment_url":"https://api.github.com/repos/binwiederhier/dabble/issues/comments{/number}","contents_url":"https://api.github.com/repos/binwiederhier/dabble/contents/{+path}","compare_url":"https://api.github.com/repos/binwiederhier/dabble/compare/{base}...{head}","merges_url":"https://api.github.com/repos/binwiederhier/dabble/merges","archive_url":"https://api.github.com/repos/binwiederhier/dabble/{archive_format}{/ref}","downloads_url":"https://api.github.com/repos/binwiederhier/dabble/downloads","issues_url":"https://api.github.com/repos/binwiederhier/dabble/issues{/number}","pulls_url":"https://api.github.com/repos/binwiederhier/dabble/pulls{/number}","milestones_url":"https://api.github.com/repos/binwiederhier/dabble/milestones{/number}","notifications_url":"https://api.github.com/repos/binwiederhier/dabble/notifications{?since,all,participating}","labels_url":"https://api.github.com/repos/binwiederhier/dabble/labels{/name}","releases_url":"https://api.github.com/repos/binwiederhier/dabble/releases{/id}","deployments_url":"https://api.github.com/repos/binwiederhier/dabble/deployments","created_at":"2022-03-15T15:06:17Z","updated_at":"2022-03-15T15:06:17Z","pushed_at":"2024-03-21T02:52:10Z","git_url":"git://github.com/binwiederhier/dabble.git","ssh_url":"git@github.com:binwiederhier/dabble.git","clone_url":"https://github.com/binwiederhier/dabble.git","svn_url":"https://github.com/binwiederhier/dabble","homepage":null,"size":1,"stargazers_count":0,"watchers_count":0,"language":null,"has_issues":true,"has_projects":true,"has_downloads":true,"has_wiki":true,"has_pages":false,"has_discussions":false,"forks_count":0,"mirror_url":null,"archived":false,"disabled":false,"open_issues_count":1,"license":null,"allow_forking":true,"is_template":false,"web_commit_signoff_required":false,"topics":[],"visibility":"public","forks":0,"open_issues":1,"watchers":0,"default_branch":"main","allow_squash_merge":true,"allow_merge_commit":true,"allow_rebase_merge":true,"allow_auto_merge":false,"delete_branch_on_merge":false,"allow_update_branch":false,"use_squash_pr_title_as_default":false,"squash_merge_commit_message":"COMMIT_MESSAGES","squash_merge_commit_title":"COMMIT_OR_PR_TITLE","merge_commit_message":"PR_TITLE","merge_commit_title":"MERGE_MESSAGE"}},"_links":{"self":{"href":"https://api.github.com/repos/binwiederhier/dabble/pulls/1"},"html":{"href":"https://github.com/binwiederhier/dabble/pull/1"},"issue":{"href":"https://api.github.com/repos/binwiederhier/dabble/issues/1"},"comments":{"href":"https://api.github.com/repos/binwiederhier/dabble/issues/1/comments"},"review_comments":{"href":"https://api.github.com/repos/binwiederhier/dabble/pulls/1/comments"},"review_comment":{"href":"https://api.github.com/repos/binwiederhier/dabble/pulls/comments{/number}"},"commits":{"href":"https://api.github.com/repos/binwiederhier/dabble/pulls/1/commits"},"statuses":{"href":"https://api.github.com/repos/binwiederhier/dabble/statuses/5703842cc5715ed1e358d23ebb693db09747ae9b"}},"author_association":"OWNER","auto_merge":null,"active_lock_reason":null,"merged":false,"mergeable":null,"rebaseable":null,"mergeable_state":"unknown","merged_by":null,"comments":0,"review_comments":0,"maintainer_can_modify":false,"commits":1,"additions":1,"deletions":1,"changed_files":1},"repository":{"id":470212003,"node_id":"R_kgDOHAbdow","name":"dabble","full_name":"binwiederhier/dabble","private":false,"owner":{"login":"binwiederhier","id":664597,"node_id":"MDQ6VXNlcjY2NDU5Nw==","avatar_url":"https://avatars.githubusercontent.com/u/664597?v=4","gravatar_id":"","url":"https://api.github.com/users/binwiederhier","html_url":"https://github.com/binwiederhier","followers_url":"https://api.github.com/users/binwiederhier/followers","following_url":"https://api.github.com/users/binwiederhier/following{/other_user}","gists_url":"https://api.github.com/users/binwiederhier/gists{/gist_id}","starred_url":"https://api.github.com/users/binwiederhier/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/binwiederhier/subscriptions","organizations_url":"https://api.github.com/users/binwiederhier/orgs","repos_url":"https://api.github.com/users/binwiederhier/repos","events_url":"https://api.github.com/users/binwiederhier/events{/privacy}","received_events_url":"https://api.github.com/users/binwiederhier/received_events","type":"User","site_admin":false},"html_url":"https://github.com/binwiederhier/dabble","description":"A repo for dabbling","fork":false,"url":"https://api.github.com/repos/binwiederhier/dabble","forks_url":"https://api.github.com/repos/binwiederhier/dabble/forks","keys_url":"https://api.github.com/repos/binwiederhier/dabble/keys{/key_id}","collaborators_url":"https://api.github.com/repos/binwiederhier/dabble/collaborators{/collaborator}","teams_url":"https://api.github.com/repos/binwiederhier/dabble/teams","hooks_url":"https://api.github.com/repos/binwiederhier/dabble/hooks","issue_events_url":"https://api.github.com/repos/binwiederhier/dabble/issues/events{/number}","events_url":"https://api.github.com/repos/binwiederhier/dabble/events","assignees_url":"https://api.github.com/repos/binwiederhier/dabble/assignees{/user}","branches_url":"https://api.github.com/repos/binwiederhier/dabble/branches{/branch}","tags_url":"https://api.github.com/repos/binwiederhier/dabble/tags","blobs_url":"https://api.github.com/repos/binwiederhier/dabble/git/blobs{/sha}","git_tags_url":"https://api.github.com/repos/binwiederhier/dabble/git/tags{/sha}","git_refs_url":"https://api.github.com/repos/binwiederhier/dabble/git/refs{/sha}","trees_url":"https://api.github.com/repos/binwiederhier/dabble/git/trees{/sha}","statuses_url":"https://api.github.com/repos/binwiederhier/dabble/statuses/{sha}","languages_url":"https://api.github.com/repos/binwiederhier/dabble/languages","stargazers_url":"https://api.github.com/repos/binwiederhier/dabble/stargazers","contributors_url":"https://api.github.com/repos/binwiederhier/dabble/contributors","subscribers_url":"https://api.github.com/repos/binwiederhier/dabble/subscribers","subscription_url":"https://api.github.com/repos/binwiederhier/dabble/subscription","commits_url":"https://api.github.com/repos/binwiederhier/dabble/commits{/sha}","git_commits_url":"https://api.github.com/repos/binwiederhier/dabble/git/commits{/sha}","comments_url":"https://api.github.com/repos/binwiederhier/dabble/comments{/number}","issue_comment_url":"https://api.github.com/repos/binwiederhier/dabble/issues/comments{/number}","contents_url":"https://api.github.com/repos/binwiederhier/dabble/contents/{+path}","compare_url":"https://api.github.com/repos/binwiederhier/dabble/compare/{base}...{head}","merges_url":"https://api.github.com/repos/binwiederhier/dabble/merges","archive_url":"https://api.github.com/repos/binwiederhier/dabble/{archive_format}{/ref}","downloads_url":"https://api.github.com/repos/binwiederhier/dabble/downloads","issues_url":"https://api.github.com/repos/binwiederhier/dabble/issues{/number}","pulls_url":"https://api.github.com/repos/binwiederhier/dabble/pulls{/number}","milestones_url":"https://api.github.com/repos/binwiederhier/dabble/milestones{/number}","notifications_url":"https://api.github.com/repos/binwiederhier/dabble/notifications{?since,all,participating}","labels_url":"https://api.github.com/repos/binwiederhier/dabble/labels{/name}","releases_url":"https://api.github.com/repos/binwiederhier/dabble/releases{/id}","deployments_url":"https://api.github.com/repos/binwiederhier/dabble/deployments","created_at":"2022-03-15T15:06:17Z","updated_at":"2022-03-15T15:06:17Z","pushed_at":"2024-03-21T02:52:10Z","git_url":"git://github.com/binwiederhier/dabble.git","ssh_url":"git@github.com:binwiederhier/dabble.git","clone_url":"https://github.com/binwiederhier/dabble.git","svn_url":"https://github.com/binwiederhier/dabble","homepage":null,"size":1,"stargazers_count":0,"watchers_count":0,"language":null,"has_issues":true,"has_projects":true,"has_downloads":true,"has_wiki":true,"has_pages":false,"has_discussions":false,"forks_count":0,"mirror_url":null,"archived":false,"disabled":false,"open_issues_count":1,"license":null,"allow_forking":true,"is_template":false,"web_commit_signoff_required":false,"topics":[],"visibility":"public","forks":0,"open_issues":1,"watchers":0,"default_branch":"main"},"sender":{"login":"binwiederhier","id":664597,"node_id":"MDQ6VXNlcjY2NDU5Nw==","avatar_url":"https://avatars.githubusercontent.com/u/664597?v=4","gravatar_id":"","url":"https://api.github.com/users/binwiederhier","html_url":"https://github.com/binwiederhier","followers_url":"https://api.github.com/users/binwiederhier/followers","following_url":"https://api.github.com/users/binwiederhier/following{/other_user}","gists_url":"https://api.github.com/users/binwiederhier/gists{/gist_id}","starred_url":"https://api.github.com/users/binwiederhier/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/binwiederhier/subscriptions","organizations_url":"https://api.github.com/users/binwiederhier/orgs","repos_url":"https://api.github.com/users/binwiederhier/repos","events_url":"https://api.github.com/users/binwiederhier/events{/privacy}","received_events_url":"https://api.github.com/users/binwiederhier/received_events","type":"User","site_admin":false}}`
  2588. response := request(t, s, "PUT", `/mytopic?tpl=yes&message=[{{.pull_request.head.repo.full_name}}]+Pull+request+{{if+eq+.action+"opened"}}OPENED{{else}}CLOSED{{end}}:+{{.pull_request.title}}`, body, nil)
  2589. require.Equal(t, 200, response.Code)
  2590. m := toMessage(t, response.Body.String())
  2591. require.Equal(t, "", m.Title)
  2592. require.Equal(t, `[binwiederhier/dabble] Pull request OPENED: A sample PR from Phil`, m.Message)
  2593. }
  2594. func TestServer_MessageTemplate_GitHub2(t *testing.T) {
  2595. t.Parallel()
  2596. s := newTestServer(t, newTestConfig(t))
  2597. body := `{"action":"opened","number":1,"pull_request":{"url":"https://api.github.com/repos/binwiederhier/dabble/pulls/1","id":1783420972,"node_id":"PR_kwDOHAbdo85qTNgs","html_url":"https://github.com/binwiederhier/dabble/pull/1","diff_url":"https://github.com/binwiederhier/dabble/pull/1.diff","patch_url":"https://github.com/binwiederhier/dabble/pull/1.patch","issue_url":"https://api.github.com/repos/binwiederhier/dabble/issues/1","number":1,"state":"open","locked":false,"title":"A sample PR from Phil","user":{"login":"binwiederhier","id":664597,"node_id":"MDQ6VXNlcjY2NDU5Nw==","avatar_url":"https://avatars.githubusercontent.com/u/664597?v=4","gravatar_id":"","url":"https://api.github.com/users/binwiederhier","html_url":"https://github.com/binwiederhier","followers_url":"https://api.github.com/users/binwiederhier/followers","following_url":"https://api.github.com/users/binwiederhier/following{/other_user}","gists_url":"https://api.github.com/users/binwiederhier/gists{/gist_id}","starred_url":"https://api.github.com/users/binwiederhier/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/binwiederhier/subscriptions","organizations_url":"https://api.github.com/users/binwiederhier/orgs","repos_url":"https://api.github.com/users/binwiederhier/repos","events_url":"https://api.github.com/users/binwiederhier/events{/privacy}","received_events_url":"https://api.github.com/users/binwiederhier/received_events","type":"User","site_admin":false},"body":null,"created_at":"2024-03-21T02:52:09Z","updated_at":"2024-03-21T02:52:09Z","closed_at":null,"merged_at":null,"merge_commit_sha":null,"assignee":null,"assignees":[],"requested_reviewers":[],"requested_teams":[],"labels":[],"milestone":null,"draft":false,"commits_url":"https://api.github.com/repos/binwiederhier/dabble/pulls/1/commits","review_comments_url":"https://api.github.com/repos/binwiederhier/dabble/pulls/1/comments","review_comment_url":"https://api.github.com/repos/binwiederhier/dabble/pulls/comments{/number}","comments_url":"https://api.github.com/repos/binwiederhier/dabble/issues/1/comments","statuses_url":"https://api.github.com/repos/binwiederhier/dabble/statuses/5703842cc5715ed1e358d23ebb693db09747ae9b","head":{"label":"binwiederhier:aa","ref":"aa","sha":"5703842cc5715ed1e358d23ebb693db09747ae9b","user":{"login":"binwiederhier","id":664597,"node_id":"MDQ6VXNlcjY2NDU5Nw==","avatar_url":"https://avatars.githubusercontent.com/u/664597?v=4","gravatar_id":"","url":"https://api.github.com/users/binwiederhier","html_url":"https://github.com/binwiederhier","followers_url":"https://api.github.com/users/binwiederhier/followers","following_url":"https://api.github.com/users/binwiederhier/following{/other_user}","gists_url":"https://api.github.com/users/binwiederhier/gists{/gist_id}","starred_url":"https://api.github.com/users/binwiederhier/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/binwiederhier/subscriptions","organizations_url":"https://api.github.com/users/binwiederhier/orgs","repos_url":"https://api.github.com/users/binwiederhier/repos","events_url":"https://api.github.com/users/binwiederhier/events{/privacy}","received_events_url":"https://api.github.com/users/binwiederhier/received_events","type":"User","site_admin":false},"repo":{"id":470212003,"node_id":"R_kgDOHAbdow","name":"dabble","full_name":"binwiederhier/dabble","private":false,"owner":{"login":"binwiederhier","id":664597,"node_id":"MDQ6VXNlcjY2NDU5Nw==","avatar_url":"https://avatars.githubusercontent.com/u/664597?v=4","gravatar_id":"","url":"https://api.github.com/users/binwiederhier","html_url":"https://github.com/binwiederhier","followers_url":"https://api.github.com/users/binwiederhier/followers","following_url":"https://api.github.com/users/binwiederhier/following{/other_user}","gists_url":"https://api.github.com/users/binwiederhier/gists{/gist_id}","starred_url":"https://api.github.com/users/binwiederhier/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/binwiederhier/subscriptions","organizations_url":"https://api.github.com/users/binwiederhier/orgs","repos_url":"https://api.github.com/users/binwiederhier/repos","events_url":"https://api.github.com/users/binwiederhier/events{/privacy}","received_events_url":"https://api.github.com/users/binwiederhier/received_events","type":"User","site_admin":false},"html_url":"https://github.com/binwiederhier/dabble","description":"A repo for dabbling","fork":false,"url":"https://api.github.com/repos/binwiederhier/dabble","forks_url":"https://api.github.com/repos/binwiederhier/dabble/forks","keys_url":"https://api.github.com/repos/binwiederhier/dabble/keys{/key_id}","collaborators_url":"https://api.github.com/repos/binwiederhier/dabble/collaborators{/collaborator}","teams_url":"https://api.github.com/repos/binwiederhier/dabble/teams","hooks_url":"https://api.github.com/repos/binwiederhier/dabble/hooks","issue_events_url":"https://api.github.com/repos/binwiederhier/dabble/issues/events{/number}","events_url":"https://api.github.com/repos/binwiederhier/dabble/events","assignees_url":"https://api.github.com/repos/binwiederhier/dabble/assignees{/user}","branches_url":"https://api.github.com/repos/binwiederhier/dabble/branches{/branch}","tags_url":"https://api.github.com/repos/binwiederhier/dabble/tags","blobs_url":"https://api.github.com/repos/binwiederhier/dabble/git/blobs{/sha}","git_tags_url":"https://api.github.com/repos/binwiederhier/dabble/git/tags{/sha}","git_refs_url":"https://api.github.com/repos/binwiederhier/dabble/git/refs{/sha}","trees_url":"https://api.github.com/repos/binwiederhier/dabble/git/trees{/sha}","statuses_url":"https://api.github.com/repos/binwiederhier/dabble/statuses/{sha}","languages_url":"https://api.github.com/repos/binwiederhier/dabble/languages","stargazers_url":"https://api.github.com/repos/binwiederhier/dabble/stargazers","contributors_url":"https://api.github.com/repos/binwiederhier/dabble/contributors","subscribers_url":"https://api.github.com/repos/binwiederhier/dabble/subscribers","subscription_url":"https://api.github.com/repos/binwiederhier/dabble/subscription","commits_url":"https://api.github.com/repos/binwiederhier/dabble/commits{/sha}","git_commits_url":"https://api.github.com/repos/binwiederhier/dabble/git/commits{/sha}","comments_url":"https://api.github.com/repos/binwiederhier/dabble/comments{/number}","issue_comment_url":"https://api.github.com/repos/binwiederhier/dabble/issues/comments{/number}","contents_url":"https://api.github.com/repos/binwiederhier/dabble/contents/{+path}","compare_url":"https://api.github.com/repos/binwiederhier/dabble/compare/{base}...{head}","merges_url":"https://api.github.com/repos/binwiederhier/dabble/merges","archive_url":"https://api.github.com/repos/binwiederhier/dabble/{archive_format}{/ref}","downloads_url":"https://api.github.com/repos/binwiederhier/dabble/downloads","issues_url":"https://api.github.com/repos/binwiederhier/dabble/issues{/number}","pulls_url":"https://api.github.com/repos/binwiederhier/dabble/pulls{/number}","milestones_url":"https://api.github.com/repos/binwiederhier/dabble/milestones{/number}","notifications_url":"https://api.github.com/repos/binwiederhier/dabble/notifications{?since,all,participating}","labels_url":"https://api.github.com/repos/binwiederhier/dabble/labels{/name}","releases_url":"https://api.github.com/repos/binwiederhier/dabble/releases{/id}","deployments_url":"https://api.github.com/repos/binwiederhier/dabble/deployments","created_at":"2022-03-15T15:06:17Z","updated_at":"2022-03-15T15:06:17Z","pushed_at":"2024-03-21T02:52:10Z","git_url":"git://github.com/binwiederhier/dabble.git","ssh_url":"git@github.com:binwiederhier/dabble.git","clone_url":"https://github.com/binwiederhier/dabble.git","svn_url":"https://github.com/binwiederhier/dabble","homepage":null,"size":1,"stargazers_count":0,"watchers_count":0,"language":null,"has_issues":true,"has_projects":true,"has_downloads":true,"has_wiki":true,"has_pages":false,"has_discussions":false,"forks_count":0,"mirror_url":null,"archived":false,"disabled":false,"open_issues_count":1,"license":null,"allow_forking":true,"is_template":false,"web_commit_signoff_required":false,"topics":[],"visibility":"public","forks":0,"open_issues":1,"watchers":0,"default_branch":"main","allow_squash_merge":true,"allow_merge_commit":true,"allow_rebase_merge":true,"allow_auto_merge":false,"delete_branch_on_merge":false,"allow_update_branch":false,"use_squash_pr_title_as_default":false,"squash_merge_commit_message":"COMMIT_MESSAGES","squash_merge_commit_title":"COMMIT_OR_PR_TITLE","merge_commit_message":"PR_TITLE","merge_commit_title":"MERGE_MESSAGE"}},"base":{"label":"binwiederhier:main","ref":"main","sha":"72d931a20bb83d123ab45accaf761150c8b01211","user":{"login":"binwiederhier","id":664597,"node_id":"MDQ6VXNlcjY2NDU5Nw==","avatar_url":"https://avatars.githubusercontent.com/u/664597?v=4","gravatar_id":"","url":"https://api.github.com/users/binwiederhier","html_url":"https://github.com/binwiederhier","followers_url":"https://api.github.com/users/binwiederhier/followers","following_url":"https://api.github.com/users/binwiederhier/following{/other_user}","gists_url":"https://api.github.com/users/binwiederhier/gists{/gist_id}","starred_url":"https://api.github.com/users/binwiederhier/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/binwiederhier/subscriptions","organizations_url":"https://api.github.com/users/binwiederhier/orgs","repos_url":"https://api.github.com/users/binwiederhier/repos","events_url":"https://api.github.com/users/binwiederhier/events{/privacy}","received_events_url":"https://api.github.com/users/binwiederhier/received_events","type":"User","site_admin":false},"repo":{"id":470212003,"node_id":"R_kgDOHAbdow","name":"dabble","full_name":"binwiederhier/dabble","private":false,"owner":{"login":"binwiederhier","id":664597,"node_id":"MDQ6VXNlcjY2NDU5Nw==","avatar_url":"https://avatars.githubusercontent.com/u/664597?v=4","gravatar_id":"","url":"https://api.github.com/users/binwiederhier","html_url":"https://github.com/binwiederhier","followers_url":"https://api.github.com/users/binwiederhier/followers","following_url":"https://api.github.com/users/binwiederhier/following{/other_user}","gists_url":"https://api.github.com/users/binwiederhier/gists{/gist_id}","starred_url":"https://api.github.com/users/binwiederhier/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/binwiederhier/subscriptions","organizations_url":"https://api.github.com/users/binwiederhier/orgs","repos_url":"https://api.github.com/users/binwiederhier/repos","events_url":"https://api.github.com/users/binwiederhier/events{/privacy}","received_events_url":"https://api.github.com/users/binwiederhier/received_events","type":"User","site_admin":false},"html_url":"https://github.com/binwiederhier/dabble","description":"A repo for dabbling","fork":false,"url":"https://api.github.com/repos/binwiederhier/dabble","forks_url":"https://api.github.com/repos/binwiederhier/dabble/forks","keys_url":"https://api.github.com/repos/binwiederhier/dabble/keys{/key_id}","collaborators_url":"https://api.github.com/repos/binwiederhier/dabble/collaborators{/collaborator}","teams_url":"https://api.github.com/repos/binwiederhier/dabble/teams","hooks_url":"https://api.github.com/repos/binwiederhier/dabble/hooks","issue_events_url":"https://api.github.com/repos/binwiederhier/dabble/issues/events{/number}","events_url":"https://api.github.com/repos/binwiederhier/dabble/events","assignees_url":"https://api.github.com/repos/binwiederhier/dabble/assignees{/user}","branches_url":"https://api.github.com/repos/binwiederhier/dabble/branches{/branch}","tags_url":"https://api.github.com/repos/binwiederhier/dabble/tags","blobs_url":"https://api.github.com/repos/binwiederhier/dabble/git/blobs{/sha}","git_tags_url":"https://api.github.com/repos/binwiederhier/dabble/git/tags{/sha}","git_refs_url":"https://api.github.com/repos/binwiederhier/dabble/git/refs{/sha}","trees_url":"https://api.github.com/repos/binwiederhier/dabble/git/trees{/sha}","statuses_url":"https://api.github.com/repos/binwiederhier/dabble/statuses/{sha}","languages_url":"https://api.github.com/repos/binwiederhier/dabble/languages","stargazers_url":"https://api.github.com/repos/binwiederhier/dabble/stargazers","contributors_url":"https://api.github.com/repos/binwiederhier/dabble/contributors","subscribers_url":"https://api.github.com/repos/binwiederhier/dabble/subscribers","subscription_url":"https://api.github.com/repos/binwiederhier/dabble/subscription","commits_url":"https://api.github.com/repos/binwiederhier/dabble/commits{/sha}","git_commits_url":"https://api.github.com/repos/binwiederhier/dabble/git/commits{/sha}","comments_url":"https://api.github.com/repos/binwiederhier/dabble/comments{/number}","issue_comment_url":"https://api.github.com/repos/binwiederhier/dabble/issues/comments{/number}","contents_url":"https://api.github.com/repos/binwiederhier/dabble/contents/{+path}","compare_url":"https://api.github.com/repos/binwiederhier/dabble/compare/{base}...{head}","merges_url":"https://api.github.com/repos/binwiederhier/dabble/merges","archive_url":"https://api.github.com/repos/binwiederhier/dabble/{archive_format}{/ref}","downloads_url":"https://api.github.com/repos/binwiederhier/dabble/downloads","issues_url":"https://api.github.com/repos/binwiederhier/dabble/issues{/number}","pulls_url":"https://api.github.com/repos/binwiederhier/dabble/pulls{/number}","milestones_url":"https://api.github.com/repos/binwiederhier/dabble/milestones{/number}","notifications_url":"https://api.github.com/repos/binwiederhier/dabble/notifications{?since,all,participating}","labels_url":"https://api.github.com/repos/binwiederhier/dabble/labels{/name}","releases_url":"https://api.github.com/repos/binwiederhier/dabble/releases{/id}","deployments_url":"https://api.github.com/repos/binwiederhier/dabble/deployments","created_at":"2022-03-15T15:06:17Z","updated_at":"2022-03-15T15:06:17Z","pushed_at":"2024-03-21T02:52:10Z","git_url":"git://github.com/binwiederhier/dabble.git","ssh_url":"git@github.com:binwiederhier/dabble.git","clone_url":"https://github.com/binwiederhier/dabble.git","svn_url":"https://github.com/binwiederhier/dabble","homepage":null,"size":1,"stargazers_count":0,"watchers_count":0,"language":null,"has_issues":true,"has_projects":true,"has_downloads":true,"has_wiki":true,"has_pages":false,"has_discussions":false,"forks_count":0,"mirror_url":null,"archived":false,"disabled":false,"open_issues_count":1,"license":null,"allow_forking":true,"is_template":false,"web_commit_signoff_required":false,"topics":[],"visibility":"public","forks":0,"open_issues":1,"watchers":0,"default_branch":"main","allow_squash_merge":true,"allow_merge_commit":true,"allow_rebase_merge":true,"allow_auto_merge":false,"delete_branch_on_merge":false,"allow_update_branch":false,"use_squash_pr_title_as_default":false,"squash_merge_commit_message":"COMMIT_MESSAGES","squash_merge_commit_title":"COMMIT_OR_PR_TITLE","merge_commit_message":"PR_TITLE","merge_commit_title":"MERGE_MESSAGE"}},"_links":{"self":{"href":"https://api.github.com/repos/binwiederhier/dabble/pulls/1"},"html":{"href":"https://github.com/binwiederhier/dabble/pull/1"},"issue":{"href":"https://api.github.com/repos/binwiederhier/dabble/issues/1"},"comments":{"href":"https://api.github.com/repos/binwiederhier/dabble/issues/1/comments"},"review_comments":{"href":"https://api.github.com/repos/binwiederhier/dabble/pulls/1/comments"},"review_comment":{"href":"https://api.github.com/repos/binwiederhier/dabble/pulls/comments{/number}"},"commits":{"href":"https://api.github.com/repos/binwiederhier/dabble/pulls/1/commits"},"statuses":{"href":"https://api.github.com/repos/binwiederhier/dabble/statuses/5703842cc5715ed1e358d23ebb693db09747ae9b"}},"author_association":"OWNER","auto_merge":null,"active_lock_reason":null,"merged":false,"mergeable":null,"rebaseable":null,"mergeable_state":"unknown","merged_by":null,"comments":0,"review_comments":0,"maintainer_can_modify":false,"commits":1,"additions":1,"deletions":1,"changed_files":1},"repository":{"id":470212003,"node_id":"R_kgDOHAbdow","name":"dabble","full_name":"binwiederhier/dabble","private":false,"owner":{"login":"binwiederhier","id":664597,"node_id":"MDQ6VXNlcjY2NDU5Nw==","avatar_url":"https://avatars.githubusercontent.com/u/664597?v=4","gravatar_id":"","url":"https://api.github.com/users/binwiederhier","html_url":"https://github.com/binwiederhier","followers_url":"https://api.github.com/users/binwiederhier/followers","following_url":"https://api.github.com/users/binwiederhier/following{/other_user}","gists_url":"https://api.github.com/users/binwiederhier/gists{/gist_id}","starred_url":"https://api.github.com/users/binwiederhier/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/binwiederhier/subscriptions","organizations_url":"https://api.github.com/users/binwiederhier/orgs","repos_url":"https://api.github.com/users/binwiederhier/repos","events_url":"https://api.github.com/users/binwiederhier/events{/privacy}","received_events_url":"https://api.github.com/users/binwiederhier/received_events","type":"User","site_admin":false},"html_url":"https://github.com/binwiederhier/dabble","description":"A repo for dabbling","fork":false,"url":"https://api.github.com/repos/binwiederhier/dabble","forks_url":"https://api.github.com/repos/binwiederhier/dabble/forks","keys_url":"https://api.github.com/repos/binwiederhier/dabble/keys{/key_id}","collaborators_url":"https://api.github.com/repos/binwiederhier/dabble/collaborators{/collaborator}","teams_url":"https://api.github.com/repos/binwiederhier/dabble/teams","hooks_url":"https://api.github.com/repos/binwiederhier/dabble/hooks","issue_events_url":"https://api.github.com/repos/binwiederhier/dabble/issues/events{/number}","events_url":"https://api.github.com/repos/binwiederhier/dabble/events","assignees_url":"https://api.github.com/repos/binwiederhier/dabble/assignees{/user}","branches_url":"https://api.github.com/repos/binwiederhier/dabble/branches{/branch}","tags_url":"https://api.github.com/repos/binwiederhier/dabble/tags","blobs_url":"https://api.github.com/repos/binwiederhier/dabble/git/blobs{/sha}","git_tags_url":"https://api.github.com/repos/binwiederhier/dabble/git/tags{/sha}","git_refs_url":"https://api.github.com/repos/binwiederhier/dabble/git/refs{/sha}","trees_url":"https://api.github.com/repos/binwiederhier/dabble/git/trees{/sha}","statuses_url":"https://api.github.com/repos/binwiederhier/dabble/statuses/{sha}","languages_url":"https://api.github.com/repos/binwiederhier/dabble/languages","stargazers_url":"https://api.github.com/repos/binwiederhier/dabble/stargazers","contributors_url":"https://api.github.com/repos/binwiederhier/dabble/contributors","subscribers_url":"https://api.github.com/repos/binwiederhier/dabble/subscribers","subscription_url":"https://api.github.com/repos/binwiederhier/dabble/subscription","commits_url":"https://api.github.com/repos/binwiederhier/dabble/commits{/sha}","git_commits_url":"https://api.github.com/repos/binwiederhier/dabble/git/commits{/sha}","comments_url":"https://api.github.com/repos/binwiederhier/dabble/comments{/number}","issue_comment_url":"https://api.github.com/repos/binwiederhier/dabble/issues/comments{/number}","contents_url":"https://api.github.com/repos/binwiederhier/dabble/contents/{+path}","compare_url":"https://api.github.com/repos/binwiederhier/dabble/compare/{base}...{head}","merges_url":"https://api.github.com/repos/binwiederhier/dabble/merges","archive_url":"https://api.github.com/repos/binwiederhier/dabble/{archive_format}{/ref}","downloads_url":"https://api.github.com/repos/binwiederhier/dabble/downloads","issues_url":"https://api.github.com/repos/binwiederhier/dabble/issues{/number}","pulls_url":"https://api.github.com/repos/binwiederhier/dabble/pulls{/number}","milestones_url":"https://api.github.com/repos/binwiederhier/dabble/milestones{/number}","notifications_url":"https://api.github.com/repos/binwiederhier/dabble/notifications{?since,all,participating}","labels_url":"https://api.github.com/repos/binwiederhier/dabble/labels{/name}","releases_url":"https://api.github.com/repos/binwiederhier/dabble/releases{/id}","deployments_url":"https://api.github.com/repos/binwiederhier/dabble/deployments","created_at":"2022-03-15T15:06:17Z","updated_at":"2022-03-15T15:06:17Z","pushed_at":"2024-03-21T02:52:10Z","git_url":"git://github.com/binwiederhier/dabble.git","ssh_url":"git@github.com:binwiederhier/dabble.git","clone_url":"https://github.com/binwiederhier/dabble.git","svn_url":"https://github.com/binwiederhier/dabble","homepage":null,"size":1,"stargazers_count":0,"watchers_count":0,"language":null,"has_issues":true,"has_projects":true,"has_downloads":true,"has_wiki":true,"has_pages":false,"has_discussions":false,"forks_count":0,"mirror_url":null,"archived":false,"disabled":false,"open_issues_count":1,"license":null,"allow_forking":true,"is_template":false,"web_commit_signoff_required":false,"topics":[],"visibility":"public","forks":0,"open_issues":1,"watchers":0,"default_branch":"main"},"sender":{"login":"binwiederhier","id":664597,"node_id":"MDQ6VXNlcjY2NDU5Nw==","avatar_url":"https://avatars.githubusercontent.com/u/664597?v=4","gravatar_id":"","url":"https://api.github.com/users/binwiederhier","html_url":"https://github.com/binwiederhier","followers_url":"https://api.github.com/users/binwiederhier/followers","following_url":"https://api.github.com/users/binwiederhier/following{/other_user}","gists_url":"https://api.github.com/users/binwiederhier/gists{/gist_id}","starred_url":"https://api.github.com/users/binwiederhier/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/binwiederhier/subscriptions","organizations_url":"https://api.github.com/users/binwiederhier/orgs","repos_url":"https://api.github.com/users/binwiederhier/repos","events_url":"https://api.github.com/users/binwiederhier/events{/privacy}","received_events_url":"https://api.github.com/users/binwiederhier/received_events","type":"User","site_admin":false}}`
  2598. response := request(t, s, "PUT", `/mytopic?tpl=yes&title={{if+eq+.action+"opened"}}New+PR:+%23{{.number}}+by+{{.pull_request.user.login}}{{else}}[{{.action}}]+PR:+%23{{.number}}+by+{{.pull_request.user.login}}{{end}}&message={{.pull_request.title}}+in+{{.repository.full_name}}.+View+more+at+{{.pull_request.html_url}}`, body, nil)
  2599. require.Equal(t, 200, response.Code)
  2600. m := toMessage(t, response.Body.String())
  2601. require.Equal(t, `New PR: #1 by binwiederhier`, m.Title)
  2602. require.Equal(t, `A sample PR from Phil in binwiederhier/dabble. View more at https://github.com/binwiederhier/dabble/pull/1`, m.Message)
  2603. }
  2604. func TestServer_MessageTemplate_DisallowedCalls(t *testing.T) {
  2605. t.Parallel()
  2606. s := newTestServer(t, newTestConfig(t))
  2607. disallowedTemplates := []string{
  2608. `{{template ""}}`,
  2609. `{{- template ""}}`,
  2610. `{{-
  2611. template ""}}`,
  2612. `{{ call abc}}`,
  2613. `{{ define "aa"}}`,
  2614. `We cannot {{define "aa"}}`,
  2615. `We cannot {{ call "aa"}}`,
  2616. `We cannot {{- template "aa"}}`,
  2617. }
  2618. for _, disallowedTemplate := range disallowedTemplates {
  2619. messageTemplate := disallowedTemplate
  2620. t.Run(disallowedTemplate, func(t *testing.T) {
  2621. t.Parallel()
  2622. response := request(t, s, "PUT", `/mytopic`, `{}`, map[string]string{
  2623. "Template": "yes",
  2624. "Message": messageTemplate,
  2625. })
  2626. require.Equal(t, 400, response.Code)
  2627. require.Equal(t, 40044, toHTTPError(t, response.Body.String()).Code)
  2628. })
  2629. }
  2630. }
  2631. func TestServer_MessageTemplate_SprigFunctions(t *testing.T) {
  2632. t.Parallel()
  2633. s := newTestServer(t, newTestConfig(t))
  2634. bodies := []string{
  2635. `{"foo":"bar","nested":{"title":"here"}}`,
  2636. `{"topic":"ntfy-test"}`,
  2637. `{"topic":"another-topic"}`,
  2638. }
  2639. templates := []string{
  2640. `{{.foo | upper}} is {{.nested.title | repeat 3}}`,
  2641. `{{if hasPrefix "ntfy-" .topic}}Topic: {{trimPrefix "ntfy-" .topic}}{{ else }}Topic: {{.topic}}{{end}}`,
  2642. `{{if hasPrefix "ntfy-" .topic}}Topic: {{trimPrefix "ntfy-" .topic}}{{ else }}Topic: {{.topic}}{{end}}`,
  2643. }
  2644. targets := []string{
  2645. `BAR is hereherehere`,
  2646. `Topic: test`,
  2647. `Topic: another-topic`,
  2648. }
  2649. for i, body := range bodies {
  2650. template := templates[i]
  2651. target := targets[i]
  2652. t.Run(template, func(t *testing.T) {
  2653. response := request(t, s, "PUT", `/mytopic`, body, map[string]string{
  2654. "Template": "yes",
  2655. "Message": template,
  2656. })
  2657. require.Equal(t, 200, response.Code)
  2658. m := toMessage(t, response.Body.String())
  2659. require.Equal(t, target, m.Message)
  2660. })
  2661. }
  2662. }
  2663. func TestServer_MessageTemplate_UnsafeSprigFunctions(t *testing.T) {
  2664. t.Parallel()
  2665. s := newTestServer(t, newTestConfig(t))
  2666. response := request(t, s, "POST", "/mytopic", `{}`, map[string]string{
  2667. "X-Message": `{{ env "PATH" }}`,
  2668. "X-Template": "1",
  2669. })
  2670. require.Equal(t, 400, response.Code)
  2671. require.Equal(t, 40043, toHTTPError(t, response.Body.String()).Code)
  2672. }
  2673. func TestServer_MessageTemplate_InlineNewlines(t *testing.T) {
  2674. t.Parallel()
  2675. s := newTestServer(t, newTestConfig(t))
  2676. response := request(t, s, "PUT", "/mytopic", `{}`, map[string]string{
  2677. "X-Message": `{{"New\nlines"}}`,
  2678. "X-Title": `{{"New\nlines"}}`,
  2679. "X-Template": "1",
  2680. })
  2681. require.Equal(t, 200, response.Code)
  2682. m := toMessage(t, response.Body.String())
  2683. require.Equal(t, `New
  2684. lines`, m.Message)
  2685. require.Equal(t, `New
  2686. lines`, m.Title)
  2687. }
  2688. func TestServer_MessageTemplate_InlineNewlinesOutsideOfTemplate(t *testing.T) {
  2689. t.Parallel()
  2690. s := newTestServer(t, newTestConfig(t))
  2691. response := request(t, s, "PUT", "/mytopic", `{"foo":"bar","food":"bag"}`, map[string]string{
  2692. "X-Message": `{{.foo}}{{"\n"}}{{.food}}`,
  2693. "X-Title": `{{.food}}{{"\n"}}{{.foo}}`,
  2694. "X-Template": "1",
  2695. })
  2696. require.Equal(t, 200, response.Code)
  2697. m := toMessage(t, response.Body.String())
  2698. require.Equal(t, `bar
  2699. bag`, m.Message)
  2700. require.Equal(t, `bag
  2701. bar`, m.Title)
  2702. }
  2703. func TestServer_MessageTemplate_TemplateFileNewlines(t *testing.T) {
  2704. t.Parallel()
  2705. c := newTestConfig(t)
  2706. c.TemplateDir = t.TempDir()
  2707. require.NoError(t, os.WriteFile(filepath.Join(c.TemplateDir, "newline.yml"), []byte(`
  2708. title: |
  2709. {{.food}}{{"\n"}}{{.foo}}
  2710. message: |
  2711. {{.foo}}{{"\n"}}{{.food}}
  2712. `), 0644))
  2713. s := newTestServer(t, c)
  2714. response := request(t, s, "POST", "/mytopic?template=newline", `{"foo":"bar","food":"bag"}`, nil)
  2715. fmt.Println(response.Body.String())
  2716. require.Equal(t, 200, response.Code)
  2717. m := toMessage(t, response.Body.String())
  2718. require.Equal(t, `bar
  2719. bag`, m.Message)
  2720. require.Equal(t, `bag
  2721. bar`, m.Title)
  2722. }
  2723. var (
  2724. //go:embed testdata/webhook_github_comment_created.json
  2725. githubCommentCreatedJSON string
  2726. //go:embed testdata/webhook_github_issue_opened.json
  2727. githubIssueOpenedJSON string
  2728. )
  2729. func TestServer_MessageTemplate_FromNamedTemplate_GitHubCommentCreated(t *testing.T) {
  2730. t.Parallel()
  2731. s := newTestServer(t, newTestConfig(t))
  2732. response := request(t, s, "POST", "/mytopic?template=github", githubCommentCreatedJSON, nil)
  2733. require.Equal(t, 200, response.Code)
  2734. m := toMessage(t, response.Body.String())
  2735. require.Equal(t, "💬 New comment on issue #1389 instant alerts without Pull to refresh", m.Title)
  2736. require.Equal(t, `Commenter: https://github.com/wunter8
  2737. Repository: https://github.com/binwiederhier/ntfy
  2738. Comment link: https://github.com/binwiederhier/ntfy/issues/1389#issuecomment-3078214289
  2739. Comment:
  2740. These are the things you need to do to get iOS push notifications to work:
  2741. 1. open a browser to the web app of your ntfy instance and copy the URL (including "http://" or "https://", your domain or IP address, and any ports, and excluding any trailing slashes)
  2742. 2. put the URL you copied in the ntfy `+"`"+`base-url`+"`"+` config in server.yml or NTFY_BASE_URL in env variables
  2743. 3. put the URL you copied in the default server URL setting in the iOS ntfy app
  2744. 4. set `+"`"+`upstream-base-url`+"`"+` in server.yml or NTFY_UPSTREAM_BASE_URL in env variables to "https://ntfy.sh" (without a trailing slash)`, m.Message)
  2745. }
  2746. func TestServer_MessageTemplate_FromNamedTemplate_GitHubIssueOpened(t *testing.T) {
  2747. t.Parallel()
  2748. s := newTestServer(t, newTestConfig(t))
  2749. response := request(t, s, "POST", "/mytopic?template=github", githubIssueOpenedJSON, nil)
  2750. require.Equal(t, 200, response.Code)
  2751. m := toMessage(t, response.Body.String())
  2752. require.Equal(t, "🐛 Issue opened: #1391 http 500 error (ntfy error 50001)", m.Title)
  2753. require.Equal(t, `Opened by: https://github.com/TheUser-dev
  2754. Repository: https://github.com/binwiederhier/ntfy
  2755. Issue link: https://github.com/binwiederhier/ntfy/issues/1391
  2756. Labels: 🪲 bug
  2757. Description:
  2758. :lady_beetle: **Describe the bug**
  2759. When sending a notification (especially when it happens with multiple requests) this error occurs
  2760. :computer: **Components impacted**
  2761. ntfy server 2.13.0 in docker, debian 12 arm64
  2762. :bulb: **Screenshots and/or logs**
  2763. `+"```"+`
  2764. closed with HTTP 500 (ntfy error 50001) (error=database table is locked, http_method=POST, http_path=/_matrix/push/v1/notify, tag=http, visitor_auth_limiter_limit=0.016666666666666666, visitor_auth_limiter_tokens=30, visitor_id=ip:<edited>, visitor_ip=<edited>, visitor_messages=448, visitor_messages_limit=17280, visitor_messages_remaining=16832, visitor_request_limiter_limit=0.2, visitor_request_limiter_tokens=57.049697891799994, visitor_seen=2025-07-16T15:06:35.429Z)
  2765. `+"```"+`
  2766. :crystal_ball: **Additional context**
  2767. Looks like this has already been fixed by #498, regression?`, m.Message)
  2768. }
  2769. func TestServer_MessageTemplate_FromNamedTemplate_GitHubIssueOpened_OverrideConfigTemplate(t *testing.T) {
  2770. t.Parallel()
  2771. c := newTestConfig(t)
  2772. c.TemplateDir = t.TempDir()
  2773. require.NoError(t, os.WriteFile(filepath.Join(c.TemplateDir, "github.yml"), []byte(`
  2774. title: |
  2775. Custom title: action={{ .action }} trunctitle={{ .issue.title | trunc 10 }}
  2776. message: |
  2777. Custom message {{ .issue.number }}
  2778. `), 0644))
  2779. s := newTestServer(t, c)
  2780. response := request(t, s, "POST", "/mytopic?template=github", githubIssueOpenedJSON, nil)
  2781. fmt.Println(response.Body.String())
  2782. require.Equal(t, 200, response.Code)
  2783. m := toMessage(t, response.Body.String())
  2784. require.Equal(t, "Custom title: action=opened trunctitle=http 500 e", m.Title)
  2785. require.Equal(t, "Custom message 1391", m.Message)
  2786. }
  2787. func TestServer_MessageTemplate_Repeat9999_TooLarge(t *testing.T) {
  2788. t.Parallel()
  2789. s := newTestServer(t, newTestConfig(t))
  2790. response := request(t, s, "POST", "/mytopic", `{}`, map[string]string{
  2791. "X-Message": `{{ repeat 9999 "mystring" }}`,
  2792. "X-Template": "1",
  2793. })
  2794. require.Equal(t, 400, response.Code)
  2795. require.Equal(t, 40041, toHTTPError(t, response.Body.String()).Code)
  2796. require.Contains(t, toHTTPError(t, response.Body.String()).Message, "message or title is too large after replacing template")
  2797. }
  2798. func TestServer_MessageTemplate_Repeat10001_TooLarge(t *testing.T) {
  2799. t.Parallel()
  2800. s := newTestServer(t, newTestConfig(t))
  2801. response := request(t, s, "POST", "/mytopic", `{}`, map[string]string{
  2802. "X-Message": `{{ repeat 10001 "mystring" }}`,
  2803. "X-Template": "1",
  2804. })
  2805. require.Equal(t, 400, response.Code)
  2806. require.Equal(t, 40045, toHTTPError(t, response.Body.String()).Code)
  2807. require.Contains(t, toHTTPError(t, response.Body.String()).Message, "repeat count 10001 exceeds limit of 10000")
  2808. }
  2809. func TestServer_MessageTemplate_Until100_000(t *testing.T) {
  2810. t.Parallel()
  2811. s := newTestServer(t, newTestConfig(t))
  2812. response := request(t, s, "POST", "/mytopic", `{}`, map[string]string{
  2813. "X-Message": `{{ range $i, $e := until 100_000 }}{{end}}`,
  2814. "X-Template": "1",
  2815. })
  2816. require.Equal(t, 400, response.Code)
  2817. require.Equal(t, 40045, toHTTPError(t, response.Body.String()).Code)
  2818. require.Contains(t, toHTTPError(t, response.Body.String()).Message, "too many iterations")
  2819. }
  2820. func newTestConfig(t *testing.T) *Config {
  2821. conf := NewConfig()
  2822. conf.BaseURL = "http://127.0.0.1:12345"
  2823. conf.CacheFile = filepath.Join(t.TempDir(), "cache.db")
  2824. conf.CacheStartupQueries = "pragma journal_mode = WAL; pragma synchronous = normal; pragma temp_store = memory;"
  2825. conf.AttachmentCacheDir = t.TempDir()
  2826. conf.TemplateDir = t.TempDir()
  2827. return conf
  2828. }
  2829. func configureAuth(t *testing.T, conf *Config) *Config {
  2830. conf.AuthFile = filepath.Join(t.TempDir(), "user.db")
  2831. conf.AuthStartupQueries = "pragma journal_mode = WAL; pragma synchronous = normal; pragma temp_store = memory;"
  2832. conf.AuthBcryptCost = bcrypt.MinCost // This speeds up tests a lot
  2833. return conf
  2834. }
  2835. func newTestConfigWithAuthFile(t *testing.T) *Config {
  2836. conf := newTestConfig(t)
  2837. conf = configureAuth(t, conf)
  2838. return conf
  2839. }
  2840. func newTestConfigWithWebPush(t *testing.T) *Config {
  2841. conf := newTestConfig(t)
  2842. privateKey, publicKey, err := webpush.GenerateVAPIDKeys()
  2843. require.Nil(t, err)
  2844. conf.WebPushFile = filepath.Join(t.TempDir(), "webpush.db")
  2845. conf.WebPushEmailAddress = "testing@example.com"
  2846. conf.WebPushPrivateKey = privateKey
  2847. conf.WebPushPublicKey = publicKey
  2848. return conf
  2849. }
  2850. func newTestServer(t *testing.T, config *Config) *Server {
  2851. server, err := New(config)
  2852. require.Nil(t, err)
  2853. return server
  2854. }
  2855. func request(t *testing.T, s *Server, method, url, body string, headers map[string]string, fn ...func(r *http.Request)) *httptest.ResponseRecorder {
  2856. rr := httptest.NewRecorder()
  2857. r, err := http.NewRequest(method, url, strings.NewReader(body))
  2858. if err != nil {
  2859. t.Fatal(err)
  2860. }
  2861. r.RemoteAddr = "9.9.9.9:1234" // Used for tests
  2862. for k, v := range headers {
  2863. r.Header.Set(k, v)
  2864. }
  2865. for _, f := range fn {
  2866. f(r)
  2867. }
  2868. s.handle(rr, r)
  2869. return rr
  2870. }
  2871. func subscribe(t *testing.T, s *Server, url string, rr *httptest.ResponseRecorder) context.CancelFunc {
  2872. ctx, cancel := context.WithCancel(context.Background())
  2873. req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
  2874. if err != nil {
  2875. t.Fatal(err)
  2876. }
  2877. done := make(chan bool)
  2878. go func() {
  2879. s.handle(rr, req)
  2880. done <- true
  2881. }()
  2882. cancelAndWaitForDone := func() {
  2883. time.Sleep(200 * time.Millisecond)
  2884. cancel()
  2885. <-done
  2886. }
  2887. time.Sleep(200 * time.Millisecond)
  2888. return cancelAndWaitForDone
  2889. }
  2890. func toMessages(t *testing.T, s string) []*message {
  2891. messages := make([]*message, 0)
  2892. scanner := bufio.NewScanner(strings.NewReader(s))
  2893. for scanner.Scan() {
  2894. messages = append(messages, toMessage(t, scanner.Text()))
  2895. }
  2896. return messages
  2897. }
  2898. func toMessage(t *testing.T, s string) *message {
  2899. var m message
  2900. require.Nil(t, json.NewDecoder(strings.NewReader(s)).Decode(&m))
  2901. return &m
  2902. }
  2903. func toHTTPError(t *testing.T, s string) *errHTTP {
  2904. var e errHTTP
  2905. require.Nil(t, json.NewDecoder(strings.NewReader(s)).Decode(&e))
  2906. return &e
  2907. }
  2908. func readAll(t *testing.T, rc io.ReadCloser) string {
  2909. b, err := io.ReadAll(rc)
  2910. if err != nil {
  2911. t.Fatal(err)
  2912. }
  2913. return string(b)
  2914. }
  2915. func waitFor(t *testing.T, f func() bool) {
  2916. waitForWithMaxWait(t, 5*time.Second, f)
  2917. }
  2918. func waitForWithMaxWait(t *testing.T, maxWait time.Duration, f func() bool) {
  2919. start := time.Now()
  2920. for time.Since(start) < maxWait {
  2921. if f() {
  2922. return
  2923. }
  2924. time.Sleep(50 * time.Millisecond)
  2925. }
  2926. t.Fatalf("Function f did not succeed after %v: %v", maxWait, string(debug.Stack()))
  2927. }