server_test.go 152 KB

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