server_test.go 164 KB

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