server_test.go 150 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935
  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. subFn := func(v *visitor, msg *message) error {
  1063. return nil
  1064. }
  1065. // Publish and check last access
  1066. response := request(t, s, "POST", "/mytopic", "test", map[string]string{
  1067. "Cache": "no",
  1068. })
  1069. require.Equal(t, 200, response.Code)
  1070. waitFor(t, func() bool {
  1071. // .lastAccess set in t.Publish() -> t.Keepalive() in Goroutine
  1072. s.topics["mytopic"].mu.RLock()
  1073. defer s.topics["mytopic"].mu.RUnlock()
  1074. return s.topics["mytopic"].lastAccess.Unix() >= time.Now().Unix()-2 &&
  1075. s.topics["mytopic"].lastAccess.Unix() <= time.Now().Unix()+2
  1076. })
  1077. // Topic won't get pruned
  1078. s.execManager()
  1079. require.NotNil(t, s.topics["mytopic"])
  1080. // Fudge with last access, but subscribe, and see that it won't get pruned (because of subscriber)
  1081. subID := s.topics["mytopic"].Subscribe(subFn, "", func() {})
  1082. s.topics["mytopic"].mu.Lock()
  1083. s.topics["mytopic"].lastAccess = time.Now().Add(-17 * time.Hour)
  1084. s.topics["mytopic"].mu.Unlock()
  1085. s.execManager()
  1086. require.NotNil(t, s.topics["mytopic"])
  1087. // It'll finally get pruned now that there are no subscribers and last access is 17 hours ago
  1088. s.topics["mytopic"].Unsubscribe(subID)
  1089. s.execManager()
  1090. require.Nil(t, s.topics["mytopic"])
  1091. }
  1092. func TestServer_TopicKeepaliveOnPoll(t *testing.T) {
  1093. t.Parallel()
  1094. s := newTestServer(t, newTestConfig(t))
  1095. // Create topic by polling once
  1096. response := request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  1097. require.Equal(t, 200, response.Code)
  1098. // Mess with last access time
  1099. s.topics["mytopic"].lastAccess = time.Now().Add(-17 * time.Hour)
  1100. // Poll again and check keepalive time
  1101. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  1102. require.Equal(t, 200, response.Code)
  1103. require.True(t, s.topics["mytopic"].lastAccess.Unix() >= time.Now().Unix()-2)
  1104. require.True(t, s.topics["mytopic"].lastAccess.Unix() <= time.Now().Unix()+2)
  1105. }
  1106. func TestServer_UnifiedPushDiscovery(t *testing.T) {
  1107. s := newTestServer(t, newTestConfig(t))
  1108. response := request(t, s, "GET", "/mytopic?up=1", "", nil)
  1109. require.Equal(t, 200, response.Code)
  1110. require.Equal(t, `{"unifiedpush":{"version":1}}`+"\n", response.Body.String())
  1111. }
  1112. func TestServer_PublishUnifiedPushBinary_AndPoll(t *testing.T) {
  1113. b := make([]byte, 12) // Max length
  1114. _, err := rand.Read(b)
  1115. require.Nil(t, err)
  1116. s := newTestServer(t, newTestConfig(t))
  1117. // Register a UnifiedPush subscriber
  1118. response := request(t, s, "GET", "/up123456789012/json?poll=1", "", nil)
  1119. require.Equal(t, 200, response.Code)
  1120. // Publish message to topic
  1121. response = request(t, s, "PUT", "/up123456789012?up=1", string(b), nil)
  1122. require.Equal(t, 200, response.Code)
  1123. m := toMessage(t, response.Body.String())
  1124. require.Equal(t, "base64", m.Encoding)
  1125. b2, err := base64.StdEncoding.DecodeString(m.Message)
  1126. require.Nil(t, err)
  1127. require.Equal(t, b, b2)
  1128. // Retrieve and check published message
  1129. response = request(t, s, "GET", "/up123456789012/json?poll=1", string(b), nil)
  1130. require.Equal(t, 200, response.Code)
  1131. m = toMessage(t, response.Body.String())
  1132. require.Equal(t, "base64", m.Encoding)
  1133. b2, err = base64.StdEncoding.DecodeString(m.Message)
  1134. require.Nil(t, err)
  1135. require.Equal(t, b, b2)
  1136. }
  1137. func TestServer_PublishUnifiedPushBinary_Truncated(t *testing.T) {
  1138. b := make([]byte, 5000) // Longer than max length
  1139. _, err := rand.Read(b)
  1140. require.Nil(t, err)
  1141. s := newTestServer(t, newTestConfig(t))
  1142. // Register a UnifiedPush subscriber
  1143. response := request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  1144. require.Equal(t, 200, response.Code)
  1145. // Publish message to topic
  1146. response = request(t, s, "PUT", "/mytopic?up=1", string(b), nil)
  1147. require.Equal(t, 200, response.Code)
  1148. m := toMessage(t, response.Body.String())
  1149. require.Equal(t, "base64", m.Encoding)
  1150. b2, err := base64.StdEncoding.DecodeString(m.Message)
  1151. require.Nil(t, err)
  1152. require.Equal(t, 4096, len(b2))
  1153. require.Equal(t, b[:4096], b2)
  1154. }
  1155. func TestServer_PublishUnifiedPushText(t *testing.T) {
  1156. s := newTestServer(t, newTestConfig(t))
  1157. // Register a UnifiedPush subscriber
  1158. response := request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  1159. require.Equal(t, 200, response.Code)
  1160. // Publish UnifiedPush text message
  1161. response = request(t, s, "PUT", "/mytopic?up=1", "this is a unifiedpush text message", nil)
  1162. require.Equal(t, 200, response.Code)
  1163. m := toMessage(t, response.Body.String())
  1164. require.Equal(t, "", m.Encoding)
  1165. require.Equal(t, "this is a unifiedpush text message", m.Message)
  1166. }
  1167. func TestServer_MatrixGateway_Discovery_Success(t *testing.T) {
  1168. s := newTestServer(t, newTestConfig(t))
  1169. response := request(t, s, "GET", "/_matrix/push/v1/notify", "", nil)
  1170. require.Equal(t, 200, response.Code)
  1171. require.Equal(t, `{"unifiedpush":{"gateway":"matrix"}}`+"\n", response.Body.String())
  1172. }
  1173. func TestServer_MatrixGateway_Discovery_Failure_Unconfigured(t *testing.T) {
  1174. c := newTestConfig(t)
  1175. c.BaseURL = ""
  1176. s := newTestServer(t, c)
  1177. response := request(t, s, "GET", "/_matrix/push/v1/notify", "", nil)
  1178. require.Equal(t, 500, response.Code)
  1179. err := toHTTPError(t, response.Body.String())
  1180. require.Equal(t, 50003, err.Code)
  1181. }
  1182. func TestServer_MatrixGateway_Push_Success(t *testing.T) {
  1183. s := newTestServer(t, newTestConfig(t))
  1184. response := request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  1185. require.Equal(t, 200, response.Code)
  1186. notification := `{"notification":{"devices":[{"pushkey":"http://127.0.0.1:12345/mytopic?up=1"}]}}`
  1187. response = request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1188. require.Equal(t, 200, response.Code)
  1189. require.Equal(t, `{"rejected":[]}`+"\n", response.Body.String())
  1190. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  1191. require.Equal(t, 200, response.Code)
  1192. m := toMessage(t, response.Body.String())
  1193. require.Equal(t, notification, m.Message)
  1194. }
  1195. func TestServer_MatrixGateway_Push_Failure_NoSubscriber(t *testing.T) {
  1196. c := newTestConfig(t)
  1197. c.VisitorSubscriberRateLimiting = true
  1198. s := newTestServer(t, c)
  1199. notification := `{"notification":{"devices":[{"pushkey":"http://127.0.0.1:12345/mytopic?up=1"}]}}`
  1200. response := request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1201. require.Equal(t, 507, response.Code)
  1202. require.Equal(t, 50701, toHTTPError(t, response.Body.String()).Code)
  1203. }
  1204. func TestServer_MatrixGateway_Push_Failure_NoSubscriber_After13Hours(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. // No success if no rate visitor set (this also creates the topic in memory)
  1210. response := request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1211. require.Equal(t, 507, response.Code)
  1212. require.Equal(t, 50701, toHTTPError(t, response.Body.String()).Code)
  1213. require.Nil(t, s.topics["mytopic"].rateVisitor)
  1214. // Fake: This topic has been around for 13 hours without a rate visitor
  1215. s.topics["mytopic"].lastAccess = time.Now().Add(-13 * time.Hour)
  1216. // Same request should now return HTTP 200 with a rejected pushkey
  1217. response = request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1218. require.Equal(t, 200, response.Code)
  1219. require.Equal(t, `{"rejected":["http://127.0.0.1:12345/mytopic?up=1"]}`, strings.TrimSpace(response.Body.String()))
  1220. // Slightly unrelated: Test that topic is pruned after 16 hours
  1221. s.topics["mytopic"].lastAccess = time.Now().Add(-17 * time.Hour)
  1222. s.execManager()
  1223. require.Nil(t, s.topics["mytopic"])
  1224. }
  1225. func TestServer_MatrixGateway_Push_Failure_InvalidPushkey(t *testing.T) {
  1226. s := newTestServer(t, newTestConfig(t))
  1227. notification := `{"notification":{"devices":[{"pushkey":"http://wrong-base-url.com/mytopic?up=1"}]}}`
  1228. response := request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1229. require.Equal(t, 200, response.Code)
  1230. require.Equal(t, `{"rejected":["http://wrong-base-url.com/mytopic?up=1"]}`+"\n", response.Body.String())
  1231. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  1232. require.Equal(t, 200, response.Code)
  1233. require.Equal(t, "", response.Body.String()) // Empty!
  1234. }
  1235. func TestServer_MatrixGateway_Push_Failure_EverythingIsWrong(t *testing.T) {
  1236. s := newTestServer(t, newTestConfig(t))
  1237. notification := `{"message":"this is not really a Matrix message"}`
  1238. response := request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1239. require.Equal(t, 400, response.Code)
  1240. require.Equal(t, 40019, toHTTPError(t, response.Body.String()).Code)
  1241. notification = `this isn't even JSON'`
  1242. response = request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1243. require.Equal(t, 400, response.Code)
  1244. require.Equal(t, 40019, toHTTPError(t, response.Body.String()).Code)
  1245. }
  1246. func TestServer_MatrixGateway_Push_Failure_Unconfigured(t *testing.T) {
  1247. c := newTestConfig(t)
  1248. c.BaseURL = ""
  1249. s := newTestServer(t, c)
  1250. notification := `{"notification":{"devices":[{"pushkey":"http://127.0.0.1:12345/mytopic?up=1"}]}}`
  1251. response := request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1252. require.Equal(t, 500, response.Code)
  1253. require.Equal(t, 50003, toHTTPError(t, response.Body.String()).Code)
  1254. }
  1255. func TestServer_PublishActions_AndPoll(t *testing.T) {
  1256. s := newTestServer(t, newTestConfig(t))
  1257. response := request(t, s, "PUT", "/mytopic", "my message", map[string]string{
  1258. "Actions": "view, Open portal, https://home.nest.com/; http, Turn down, https://api.nest.com/device/XZ1D2, body=target_temp_f=65",
  1259. })
  1260. require.Equal(t, 200, response.Code)
  1261. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  1262. require.Equal(t, 200, response.Code)
  1263. m := toMessage(t, response.Body.String())
  1264. require.Equal(t, 2, len(m.Actions))
  1265. require.Equal(t, "view", m.Actions[0].Action)
  1266. require.Equal(t, "Open portal", m.Actions[0].Label)
  1267. require.Equal(t, "https://home.nest.com/", m.Actions[0].URL)
  1268. require.Equal(t, "http", m.Actions[1].Action)
  1269. require.Equal(t, "Turn down", m.Actions[1].Label)
  1270. require.Equal(t, "https://api.nest.com/device/XZ1D2", m.Actions[1].URL)
  1271. require.Equal(t, "target_temp_f=65", m.Actions[1].Body)
  1272. }
  1273. func TestServer_PublishMarkdown(t *testing.T) {
  1274. s := newTestServer(t, newTestConfig(t))
  1275. response := request(t, s, "PUT", "/mytopic", "**make this bold**", map[string]string{
  1276. "Content-Type": "text/markdown",
  1277. })
  1278. require.Equal(t, 200, response.Code)
  1279. m := toMessage(t, response.Body.String())
  1280. require.Equal(t, "**make this bold**", m.Message)
  1281. require.Equal(t, "text/markdown", m.ContentType)
  1282. }
  1283. func TestServer_PublishMarkdown_QueryParam(t *testing.T) {
  1284. s := newTestServer(t, newTestConfig(t))
  1285. response := request(t, s, "PUT", "/mytopic?md=1", "**make this bold**", nil)
  1286. require.Equal(t, 200, response.Code)
  1287. m := toMessage(t, response.Body.String())
  1288. require.Equal(t, "**make this bold**", m.Message)
  1289. require.Equal(t, "text/markdown", m.ContentType)
  1290. }
  1291. func TestServer_PublishMarkdown_NotMarkdown(t *testing.T) {
  1292. s := newTestServer(t, newTestConfig(t))
  1293. response := request(t, s, "PUT", "/mytopic", "**make this bold**", map[string]string{
  1294. "Content-Type": "not-markdown",
  1295. })
  1296. require.Equal(t, 200, response.Code)
  1297. m := toMessage(t, response.Body.String())
  1298. require.Equal(t, "", m.ContentType)
  1299. }
  1300. func TestServer_PublishAsJSON(t *testing.T) {
  1301. s := newTestServer(t, newTestConfig(t))
  1302. body := `{"topic":"mytopic","message":"A message","title":"a title\nwith lines","tags":["tag1","tag 2"],` +
  1303. `"not-a-thing":"ok", "attach":"http://google.com","filename":"google.pdf", "click":"http://ntfy.sh","priority":4,` +
  1304. `"icon":"https://ntfy.sh/static/img/ntfy.png", "delay":"30min"}`
  1305. response := request(t, s, "PUT", "/", body, nil)
  1306. require.Equal(t, 200, response.Code)
  1307. m := toMessage(t, response.Body.String())
  1308. require.Equal(t, "mytopic", m.Topic)
  1309. require.Equal(t, "A message", m.Message)
  1310. require.Equal(t, "a title\nwith lines", m.Title)
  1311. require.Equal(t, []string{"tag1", "tag 2"}, m.Tags)
  1312. require.Equal(t, "http://google.com", m.Attachment.URL)
  1313. require.Equal(t, "google.pdf", m.Attachment.Name)
  1314. require.Equal(t, "http://ntfy.sh", m.Click)
  1315. require.Equal(t, "https://ntfy.sh/static/img/ntfy.png", m.Icon)
  1316. require.Equal(t, "", m.ContentType)
  1317. require.Equal(t, 4, m.Priority)
  1318. require.True(t, m.Time > time.Now().Unix()+29*60)
  1319. require.True(t, m.Time < time.Now().Unix()+31*60)
  1320. }
  1321. func TestServer_PublishAsJSON_Markdown(t *testing.T) {
  1322. s := newTestServer(t, newTestConfig(t))
  1323. body := `{"topic":"mytopic","message":"**This is bold**","markdown":true}`
  1324. response := request(t, s, "PUT", "/", body, nil)
  1325. require.Equal(t, 200, response.Code)
  1326. m := toMessage(t, response.Body.String())
  1327. require.Equal(t, "mytopic", m.Topic)
  1328. require.Equal(t, "**This is bold**", m.Message)
  1329. require.Equal(t, "text/markdown", m.ContentType)
  1330. }
  1331. func TestServer_PublishAsJSON_RateLimit_MessageDailyLimit(t *testing.T) {
  1332. // Publishing as JSON follows a different path. This ensures that rate
  1333. // limiting works for this endpoint as well
  1334. c := newTestConfig(t)
  1335. c.VisitorMessageDailyLimit = 3
  1336. s := newTestServer(t, c)
  1337. for i := 0; i < 3; i++ {
  1338. response := request(t, s, "PUT", "/", `{"topic":"mytopic","message":"A message"}`, nil)
  1339. require.Equal(t, 200, response.Code)
  1340. }
  1341. response := request(t, s, "PUT", "/", `{"topic":"mytopic","message":"A message"}`, nil)
  1342. require.Equal(t, 429, response.Code)
  1343. require.Equal(t, 42908, toHTTPError(t, response.Body.String()).Code)
  1344. }
  1345. func TestServer_PublishAsJSON_WithEmail(t *testing.T) {
  1346. t.Parallel()
  1347. mailer := &testMailer{}
  1348. s := newTestServer(t, newTestConfig(t))
  1349. s.smtpSender = mailer
  1350. body := `{"topic":"mytopic","message":"A message","email":"phil@example.com"}`
  1351. response := request(t, s, "PUT", "/", body, nil)
  1352. require.Equal(t, 200, response.Code)
  1353. time.Sleep(100 * time.Millisecond) // E-Mail publishing happens in a Go routine
  1354. m := toMessage(t, response.Body.String())
  1355. require.Equal(t, "mytopic", m.Topic)
  1356. require.Equal(t, "A message", m.Message)
  1357. require.Equal(t, 1, mailer.Count())
  1358. }
  1359. func TestServer_PublishAsJSON_WithActions(t *testing.T) {
  1360. s := newTestServer(t, newTestConfig(t))
  1361. body := `{
  1362. "topic":"mytopic",
  1363. "message":"A message",
  1364. "actions": [
  1365. {
  1366. "action": "view",
  1367. "label": "Open portal",
  1368. "url": "https://home.nest.com/"
  1369. },
  1370. {
  1371. "action": "http",
  1372. "label": "Turn down",
  1373. "url": "https://api.nest.com/device/XZ1D2",
  1374. "body": "target_temp_f=65"
  1375. }
  1376. ]
  1377. }`
  1378. response := request(t, s, "POST", "/", body, nil)
  1379. require.Equal(t, 200, response.Code)
  1380. m := toMessage(t, response.Body.String())
  1381. require.Equal(t, "mytopic", m.Topic)
  1382. require.Equal(t, "A message", m.Message)
  1383. require.Equal(t, 2, len(m.Actions))
  1384. require.Equal(t, "view", m.Actions[0].Action)
  1385. require.Equal(t, "Open portal", m.Actions[0].Label)
  1386. require.Equal(t, "https://home.nest.com/", m.Actions[0].URL)
  1387. require.Equal(t, "http", m.Actions[1].Action)
  1388. require.Equal(t, "Turn down", m.Actions[1].Label)
  1389. require.Equal(t, "https://api.nest.com/device/XZ1D2", m.Actions[1].URL)
  1390. require.Equal(t, "target_temp_f=65", m.Actions[1].Body)
  1391. }
  1392. func TestServer_PublishAsJSON_Invalid(t *testing.T) {
  1393. s := newTestServer(t, newTestConfig(t))
  1394. body := `{"topic":"mytopic",INVALID`
  1395. response := request(t, s, "PUT", "/", body, nil)
  1396. require.Equal(t, 400, response.Code)
  1397. }
  1398. func TestServer_PublishWithTierBasedMessageLimitAndExpiry(t *testing.T) {
  1399. c := newTestConfigWithAuthFile(t)
  1400. s := newTestServer(t, c)
  1401. // Create tier with certain limits
  1402. require.Nil(t, s.userManager.AddTier(&user.Tier{
  1403. Code: "test",
  1404. MessageLimit: 5,
  1405. MessageExpiryDuration: -5 * time.Second, // Second, what a hack!
  1406. }))
  1407. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser))
  1408. require.Nil(t, s.userManager.ChangeTier("phil", "test"))
  1409. // Publish to reach message limit
  1410. for i := 0; i < 5; i++ {
  1411. response := request(t, s, "PUT", "/mytopic", fmt.Sprintf("this is message %d", i+1), map[string]string{
  1412. "Authorization": util.BasicAuth("phil", "phil"),
  1413. })
  1414. require.Equal(t, 200, response.Code)
  1415. msg := toMessage(t, response.Body.String())
  1416. require.True(t, msg.Expires < time.Now().Unix()+5)
  1417. }
  1418. response := request(t, s, "PUT", "/mytopic", "this is too much", map[string]string{
  1419. "Authorization": util.BasicAuth("phil", "phil"),
  1420. })
  1421. require.Equal(t, 429, response.Code)
  1422. // Run pruning and see if they are gone
  1423. s.execManager()
  1424. response = request(t, s, "GET", "/mytopic/json?poll=1", "", map[string]string{
  1425. "Authorization": util.BasicAuth("phil", "phil"),
  1426. })
  1427. require.Equal(t, 200, response.Code)
  1428. require.Empty(t, response.Body)
  1429. }
  1430. func TestServer_PublishAttachment(t *testing.T) {
  1431. content := "text file!" + util.RandomString(4990) // > 4096
  1432. s := newTestServer(t, newTestConfig(t))
  1433. response := request(t, s, "PUT", "/mytopic", content, nil)
  1434. msg := toMessage(t, response.Body.String())
  1435. require.Equal(t, "attachment.txt", msg.Attachment.Name)
  1436. require.Equal(t, "text/plain; charset=utf-8", msg.Attachment.Type)
  1437. require.Equal(t, int64(5000), msg.Attachment.Size)
  1438. require.GreaterOrEqual(t, msg.Attachment.Expires, time.Now().Add(179*time.Minute).Unix()) // Almost 3 hours
  1439. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1440. require.Equal(t, netip.Addr{}, msg.Sender) // Should never be returned
  1441. require.FileExists(t, filepath.Join(s.config.AttachmentCacheDir, msg.ID))
  1442. // GET
  1443. path := strings.TrimPrefix(msg.Attachment.URL, "http://127.0.0.1:12345")
  1444. response = request(t, s, "GET", path, "", nil)
  1445. require.Equal(t, 200, response.Code)
  1446. require.Equal(t, "5000", response.Header().Get("Content-Length"))
  1447. require.Equal(t, content, response.Body.String())
  1448. // HEAD
  1449. response = request(t, s, "HEAD", path, "", nil)
  1450. require.Equal(t, 200, response.Code)
  1451. require.Equal(t, "5000", response.Header().Get("Content-Length"))
  1452. require.Equal(t, "", response.Body.String())
  1453. // Slightly unrelated cross-test: make sure we add an owner for internal attachments
  1454. size, err := s.messageCache.AttachmentBytesUsedBySender("9.9.9.9") // See request()
  1455. require.Nil(t, err)
  1456. require.Equal(t, int64(5000), size)
  1457. }
  1458. func TestServer_PublishAttachmentShortWithFilename(t *testing.T) {
  1459. c := newTestConfig(t)
  1460. c.BehindProxy = true
  1461. s := newTestServer(t, c)
  1462. content := "this is an ATTACHMENT"
  1463. response := request(t, s, "PUT", "/mytopic?f=myfile.txt", content, map[string]string{
  1464. "X-Forwarded-For": "1.2.3.4",
  1465. })
  1466. msg := toMessage(t, response.Body.String())
  1467. require.Equal(t, "myfile.txt", msg.Attachment.Name)
  1468. require.Equal(t, "text/plain; charset=utf-8", msg.Attachment.Type)
  1469. require.Equal(t, int64(21), msg.Attachment.Size)
  1470. require.GreaterOrEqual(t, msg.Attachment.Expires, time.Now().Add(3*time.Hour).Unix())
  1471. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1472. require.Equal(t, netip.Addr{}, msg.Sender) // Should never be returned
  1473. require.FileExists(t, filepath.Join(s.config.AttachmentCacheDir, msg.ID))
  1474. path := strings.TrimPrefix(msg.Attachment.URL, "http://127.0.0.1:12345")
  1475. response = request(t, s, "GET", path, "", nil)
  1476. require.Equal(t, 200, response.Code)
  1477. require.Equal(t, "21", response.Header().Get("Content-Length"))
  1478. require.Equal(t, content, response.Body.String())
  1479. // Slightly unrelated cross-test: make sure we add an owner for internal attachments
  1480. size, err := s.messageCache.AttachmentBytesUsedBySender("1.2.3.4")
  1481. require.Nil(t, err)
  1482. require.Equal(t, int64(21), size)
  1483. }
  1484. func TestServer_PublishAttachmentExternalWithoutFilename(t *testing.T) {
  1485. s := newTestServer(t, newTestConfig(t))
  1486. response := request(t, s, "PUT", "/mytopic", "", map[string]string{
  1487. "Attach": "https://upload.wikimedia.org/wikipedia/commons/f/fd/Pink_flower.jpg",
  1488. })
  1489. msg := toMessage(t, response.Body.String())
  1490. require.Equal(t, "You received a file: Pink_flower.jpg", msg.Message)
  1491. require.Equal(t, "Pink_flower.jpg", msg.Attachment.Name)
  1492. require.Equal(t, "https://upload.wikimedia.org/wikipedia/commons/f/fd/Pink_flower.jpg", msg.Attachment.URL)
  1493. require.Equal(t, "", msg.Attachment.Type)
  1494. require.Equal(t, int64(0), msg.Attachment.Size)
  1495. require.Equal(t, int64(0), msg.Attachment.Expires)
  1496. require.Equal(t, netip.Addr{}, msg.Sender)
  1497. // Slightly unrelated cross-test: make sure we don't add an owner for external attachments
  1498. size, err := s.messageCache.AttachmentBytesUsedBySender("127.0.0.1")
  1499. require.Nil(t, err)
  1500. require.Equal(t, int64(0), size)
  1501. }
  1502. func TestServer_PublishAttachmentExternalWithFilename(t *testing.T) {
  1503. s := newTestServer(t, newTestConfig(t))
  1504. response := request(t, s, "PUT", "/mytopic", "This is a custom message", map[string]string{
  1505. "X-Attach": "https://upload.wikimedia.org/wikipedia/commons/f/fd/Pink_flower.jpg",
  1506. "File": "some file.jpg",
  1507. })
  1508. msg := toMessage(t, response.Body.String())
  1509. require.Equal(t, "This is a custom message", msg.Message)
  1510. require.Equal(t, "some file.jpg", msg.Attachment.Name)
  1511. require.Equal(t, "https://upload.wikimedia.org/wikipedia/commons/f/fd/Pink_flower.jpg", msg.Attachment.URL)
  1512. require.Equal(t, "", msg.Attachment.Type)
  1513. require.Equal(t, int64(0), msg.Attachment.Size)
  1514. require.Equal(t, int64(0), msg.Attachment.Expires)
  1515. require.Equal(t, netip.Addr{}, msg.Sender)
  1516. }
  1517. func TestServer_PublishAttachmentBadURL(t *testing.T) {
  1518. s := newTestServer(t, newTestConfig(t))
  1519. response := request(t, s, "PUT", "/mytopic?a=not+a+URL", "", nil)
  1520. err := toHTTPError(t, response.Body.String())
  1521. require.Equal(t, 400, response.Code)
  1522. require.Equal(t, 400, err.HTTPCode)
  1523. require.Equal(t, 40013, err.Code)
  1524. }
  1525. func TestServer_PublishAttachmentTooLargeContentLength(t *testing.T) {
  1526. content := util.RandomString(5000) // > 4096
  1527. s := newTestServer(t, newTestConfig(t))
  1528. response := request(t, s, "PUT", "/mytopic", content, map[string]string{
  1529. "Content-Length": "20000000",
  1530. })
  1531. err := toHTTPError(t, response.Body.String())
  1532. require.Equal(t, 413, response.Code)
  1533. require.Equal(t, 413, err.HTTPCode)
  1534. require.Equal(t, 41301, err.Code)
  1535. }
  1536. func TestServer_PublishAttachmentTooLargeBodyAttachmentFileSizeLimit(t *testing.T) {
  1537. content := util.RandomString(5001) // > 5000, see below
  1538. c := newTestConfig(t)
  1539. c.AttachmentFileSizeLimit = 5000
  1540. s := newTestServer(t, c)
  1541. response := request(t, s, "PUT", "/mytopic", content, nil)
  1542. err := toHTTPError(t, response.Body.String())
  1543. require.Equal(t, 413, response.Code)
  1544. require.Equal(t, 413, err.HTTPCode)
  1545. require.Equal(t, 41301, err.Code)
  1546. }
  1547. func TestServer_PublishAttachmentExpiryBeforeDelivery(t *testing.T) {
  1548. c := newTestConfig(t)
  1549. c.AttachmentExpiryDuration = 10 * time.Minute
  1550. s := newTestServer(t, c)
  1551. response := request(t, s, "PUT", "/mytopic", util.RandomString(5000), map[string]string{
  1552. "Delay": "11 min", // > AttachmentExpiryDuration
  1553. })
  1554. err := toHTTPError(t, response.Body.String())
  1555. require.Equal(t, 400, response.Code)
  1556. require.Equal(t, 400, err.HTTPCode)
  1557. require.Equal(t, 40015, err.Code)
  1558. }
  1559. func TestServer_PublishAttachmentTooLargeBodyVisitorAttachmentTotalSizeLimit(t *testing.T) {
  1560. c := newTestConfig(t)
  1561. c.VisitorAttachmentTotalSizeLimit = 10000
  1562. s := newTestServer(t, c)
  1563. response := request(t, s, "PUT", "/mytopic", "text file!"+util.RandomString(4990), nil)
  1564. msg := toMessage(t, response.Body.String())
  1565. require.Equal(t, 200, response.Code)
  1566. require.Equal(t, "You received a file: attachment.txt", msg.Message)
  1567. require.Equal(t, int64(5000), msg.Attachment.Size)
  1568. content := util.RandomString(5001) // 5000+5001 > , see below
  1569. response = request(t, s, "PUT", "/mytopic", content, nil)
  1570. err := toHTTPError(t, response.Body.String())
  1571. require.Equal(t, 413, response.Code)
  1572. require.Equal(t, 413, err.HTTPCode)
  1573. require.Equal(t, 41301, err.Code)
  1574. }
  1575. func TestServer_PublishAttachmentAndExpire(t *testing.T) {
  1576. t.Parallel()
  1577. content := util.RandomString(5000) // > 4096
  1578. c := newTestConfig(t)
  1579. c.AttachmentExpiryDuration = time.Millisecond // Hack
  1580. s := newTestServer(t, c)
  1581. // Publish and make sure we can retrieve it
  1582. response := request(t, s, "PUT", "/mytopic", content, nil)
  1583. msg := toMessage(t, response.Body.String())
  1584. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1585. file := filepath.Join(s.config.AttachmentCacheDir, msg.ID)
  1586. require.FileExists(t, file)
  1587. path := strings.TrimPrefix(msg.Attachment.URL, "http://127.0.0.1:12345")
  1588. response = request(t, s, "GET", path, "", nil)
  1589. require.Equal(t, 200, response.Code)
  1590. require.Equal(t, content, response.Body.String())
  1591. // Prune and makes sure it's gone
  1592. waitFor(t, func() bool {
  1593. s.execManager() // May run many times
  1594. return !util.FileExists(file)
  1595. })
  1596. response = request(t, s, "GET", path, "", nil)
  1597. require.Equal(t, 404, response.Code)
  1598. }
  1599. func TestServer_PublishAttachmentWithTierBasedExpiry(t *testing.T) {
  1600. t.Parallel()
  1601. content := util.RandomString(5000) // > 4096
  1602. c := newTestConfigWithAuthFile(t)
  1603. c.AttachmentExpiryDuration = time.Millisecond // Hack
  1604. s := newTestServer(t, c)
  1605. // Create tier with certain limits
  1606. sevenDays := time.Duration(604800) * time.Second
  1607. require.Nil(t, s.userManager.AddTier(&user.Tier{
  1608. Code: "test",
  1609. MessageLimit: 10,
  1610. MessageExpiryDuration: sevenDays,
  1611. AttachmentFileSizeLimit: 50_000,
  1612. AttachmentTotalSizeLimit: 200_000,
  1613. AttachmentExpiryDuration: sevenDays, // 7 days
  1614. AttachmentBandwidthLimit: 100000,
  1615. }))
  1616. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser))
  1617. require.Nil(t, s.userManager.ChangeTier("phil", "test"))
  1618. // Publish and make sure we can retrieve it
  1619. response := request(t, s, "PUT", "/mytopic", content, map[string]string{
  1620. "Authorization": util.BasicAuth("phil", "phil"),
  1621. })
  1622. require.Equal(t, 200, response.Code)
  1623. msg := toMessage(t, response.Body.String())
  1624. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1625. require.True(t, msg.Attachment.Expires > time.Now().Add(sevenDays-30*time.Second).Unix())
  1626. require.True(t, msg.Expires > time.Now().Add(sevenDays-30*time.Second).Unix())
  1627. file := filepath.Join(s.config.AttachmentCacheDir, msg.ID)
  1628. require.FileExists(t, file)
  1629. path := strings.TrimPrefix(msg.Attachment.URL, "http://127.0.0.1:12345")
  1630. response = request(t, s, "GET", path, "", nil)
  1631. require.Equal(t, 200, response.Code)
  1632. require.Equal(t, content, response.Body.String())
  1633. // Prune and makes sure it's still there
  1634. time.Sleep(time.Second) // Sigh ...
  1635. s.execManager()
  1636. require.FileExists(t, file)
  1637. response = request(t, s, "GET", path, "", nil)
  1638. require.Equal(t, 200, response.Code)
  1639. }
  1640. func TestServer_PublishAttachmentWithTierBasedBandwidthLimit(t *testing.T) {
  1641. content := util.RandomString(5000) // > 4096
  1642. c := newTestConfigWithAuthFile(t)
  1643. c.VisitorAttachmentDailyBandwidthLimit = 1000 // Much lower than tier bandwidth!
  1644. s := newTestServer(t, c)
  1645. // Create tier with certain limits
  1646. require.Nil(t, s.userManager.AddTier(&user.Tier{
  1647. Code: "test",
  1648. MessageLimit: 10,
  1649. MessageExpiryDuration: time.Hour,
  1650. AttachmentFileSizeLimit: 50_000,
  1651. AttachmentTotalSizeLimit: 200_000,
  1652. AttachmentExpiryDuration: time.Hour,
  1653. AttachmentBandwidthLimit: 14000, // < 3x5000 bytes -> enough for one upload, one download
  1654. }))
  1655. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser))
  1656. require.Nil(t, s.userManager.ChangeTier("phil", "test"))
  1657. // Publish and make sure we can retrieve it
  1658. rr := request(t, s, "PUT", "/mytopic", content, map[string]string{
  1659. "Authorization": util.BasicAuth("phil", "phil"),
  1660. })
  1661. require.Equal(t, 200, rr.Code)
  1662. msg := toMessage(t, rr.Body.String())
  1663. // Retrieve it (first time succeeds)
  1664. rr = request(t, s, "GET", "/file/"+msg.ID, content, nil) // File downloads do not send auth headers!!
  1665. require.Equal(t, 200, rr.Code)
  1666. require.Equal(t, content, rr.Body.String())
  1667. // Retrieve it AGAIN (fails, due to bandwidth limit)
  1668. rr = request(t, s, "GET", "/file/"+msg.ID, content, nil)
  1669. require.Equal(t, 429, rr.Code)
  1670. }
  1671. func TestServer_PublishAttachmentWithTierBasedLimits(t *testing.T) {
  1672. smallFile := util.RandomString(20_000)
  1673. largeFile := util.RandomString(50_000)
  1674. c := newTestConfigWithAuthFile(t)
  1675. c.AttachmentFileSizeLimit = 20_000
  1676. c.VisitorAttachmentTotalSizeLimit = 40_000
  1677. s := newTestServer(t, c)
  1678. // Create tier with certain limits
  1679. require.Nil(t, s.userManager.AddTier(&user.Tier{
  1680. Code: "test",
  1681. MessageLimit: 100,
  1682. AttachmentFileSizeLimit: 50_000,
  1683. AttachmentTotalSizeLimit: 200_000,
  1684. AttachmentExpiryDuration: 30 * time.Second,
  1685. AttachmentBandwidthLimit: 1000000,
  1686. }))
  1687. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser))
  1688. require.Nil(t, s.userManager.ChangeTier("phil", "test"))
  1689. // Publish small file as anonymous
  1690. response := request(t, s, "PUT", "/mytopic", smallFile, nil)
  1691. msg := toMessage(t, response.Body.String())
  1692. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1693. require.FileExists(t, filepath.Join(s.config.AttachmentCacheDir, msg.ID))
  1694. // Publish large file as anonymous
  1695. response = request(t, s, "PUT", "/mytopic", largeFile, nil)
  1696. require.Equal(t, 413, response.Code)
  1697. require.Equal(t, 41301, toHTTPError(t, response.Body.String()).Code)
  1698. // Publish too large file as phil
  1699. response = request(t, s, "PUT", "/mytopic", largeFile+" a few more bytes", map[string]string{
  1700. "Authorization": util.BasicAuth("phil", "phil"),
  1701. })
  1702. require.Equal(t, 413, response.Code)
  1703. require.Equal(t, 41301, toHTTPError(t, response.Body.String()).Code)
  1704. // Publish large file as phil (4x)
  1705. for i := 0; i < 4; i++ {
  1706. response = request(t, s, "PUT", "/mytopic", largeFile, map[string]string{
  1707. "Authorization": util.BasicAuth("phil", "phil"),
  1708. })
  1709. require.Equal(t, 200, response.Code)
  1710. msg = toMessage(t, response.Body.String())
  1711. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1712. require.FileExists(t, filepath.Join(s.config.AttachmentCacheDir, msg.ID))
  1713. }
  1714. response = request(t, s, "PUT", "/mytopic", largeFile, map[string]string{
  1715. "Authorization": util.BasicAuth("phil", "phil"),
  1716. })
  1717. require.Equal(t, 413, response.Code)
  1718. require.Equal(t, 41301, toHTTPError(t, response.Body.String()).Code)
  1719. }
  1720. func TestServer_PublishAttachmentBandwidthLimit(t *testing.T) {
  1721. content := util.RandomString(5000) // > 4096
  1722. c := newTestConfig(t)
  1723. c.VisitorAttachmentDailyBandwidthLimit = 5*5000 + 123 // A little more than 1 upload and 3 downloads
  1724. s := newTestServer(t, c)
  1725. // Publish attachment
  1726. response := request(t, s, "PUT", "/mytopic", content, nil)
  1727. msg := toMessage(t, response.Body.String())
  1728. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1729. // Value it 4 times successfully
  1730. path := strings.TrimPrefix(msg.Attachment.URL, "http://127.0.0.1:12345")
  1731. for i := 1; i <= 4; i++ { // 4 successful downloads
  1732. response = request(t, s, "GET", path, "", nil)
  1733. require.Equal(t, 200, response.Code)
  1734. require.Equal(t, content, response.Body.String())
  1735. }
  1736. // And then fail with a 429
  1737. response = request(t, s, "GET", path, "", nil)
  1738. err := toHTTPError(t, response.Body.String())
  1739. require.Equal(t, 429, response.Code)
  1740. require.Equal(t, 42905, err.Code)
  1741. }
  1742. func TestServer_PublishAttachmentBandwidthLimitUploadOnly(t *testing.T) {
  1743. content := util.RandomString(5000) // > 4096
  1744. c := newTestConfig(t)
  1745. c.VisitorAttachmentDailyBandwidthLimit = 5*5000 + 500 // 5 successful uploads
  1746. s := newTestServer(t, c)
  1747. // 5 successful uploads
  1748. for i := 1; i <= 5; i++ {
  1749. response := request(t, s, "PUT", "/mytopic", content, nil)
  1750. msg := toMessage(t, response.Body.String())
  1751. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1752. }
  1753. // And a failed one
  1754. response := request(t, s, "PUT", "/mytopic", content, nil)
  1755. err := toHTTPError(t, response.Body.String())
  1756. require.Equal(t, 413, response.Code)
  1757. require.Equal(t, 41301, err.Code)
  1758. }
  1759. func TestServer_PublishAttachmentAndImmediatelyGetItWithCacheTimeout(t *testing.T) {
  1760. // This tests the awkward util.Retry in handleFile: Due to the async persisting of messages,
  1761. // the message is not immediately available when attempting to download it.
  1762. c := newTestConfig(t)
  1763. c.CacheBatchTimeout = 500 * time.Millisecond
  1764. c.CacheBatchSize = 10
  1765. s := newTestServer(t, c)
  1766. content := "this is an ATTACHMENT"
  1767. rr := request(t, s, "PUT", "/mytopic?f=myfile.txt", content, nil)
  1768. m := toMessage(t, rr.Body.String())
  1769. require.Equal(t, "myfile.txt", m.Attachment.Name)
  1770. path := strings.TrimPrefix(m.Attachment.URL, "http://127.0.0.1:12345")
  1771. rr = request(t, s, "GET", path, "", nil)
  1772. require.Equal(t, 200, rr.Code) // Not 404!
  1773. require.Equal(t, content, rr.Body.String())
  1774. }
  1775. func TestServer_PublishAttachmentAccountStats(t *testing.T) {
  1776. content := util.RandomString(4999) // > 4096
  1777. c := newTestConfig(t)
  1778. c.AttachmentFileSizeLimit = 5000
  1779. c.VisitorAttachmentTotalSizeLimit = 6000
  1780. s := newTestServer(t, c)
  1781. // Upload one attachment
  1782. response := request(t, s, "PUT", "/mytopic", content, nil)
  1783. msg := toMessage(t, response.Body.String())
  1784. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1785. // User stats
  1786. response = request(t, s, "GET", "/v1/account", "", nil)
  1787. require.Equal(t, 200, response.Code)
  1788. account, err := util.UnmarshalJSON[apiAccountResponse](io.NopCloser(response.Body))
  1789. require.Nil(t, err)
  1790. require.Equal(t, int64(5000), account.Limits.AttachmentFileSize)
  1791. require.Equal(t, int64(6000), account.Limits.AttachmentTotalSize)
  1792. require.Equal(t, int64(4999), account.Stats.AttachmentTotalSize)
  1793. require.Equal(t, int64(1001), account.Stats.AttachmentTotalSizeRemaining)
  1794. require.Equal(t, int64(1), account.Stats.Messages)
  1795. }
  1796. func TestServer_Visitor_XForwardedFor_None(t *testing.T) {
  1797. c := newTestConfig(t)
  1798. c.BehindProxy = true
  1799. s := newTestServer(t, c)
  1800. r, _ := http.NewRequest("GET", "/bla", nil)
  1801. r.RemoteAddr = "8.9.10.11"
  1802. r.Header.Set("X-Forwarded-For", " ") // Spaces, not empty!
  1803. v, err := s.maybeAuthenticate(r)
  1804. require.Nil(t, err)
  1805. require.Equal(t, "8.9.10.11", v.ip.String())
  1806. }
  1807. func TestServer_Visitor_XForwardedFor_Single(t *testing.T) {
  1808. c := newTestConfig(t)
  1809. c.BehindProxy = true
  1810. s := newTestServer(t, c)
  1811. r, _ := http.NewRequest("GET", "/bla", nil)
  1812. r.RemoteAddr = "8.9.10.11"
  1813. r.Header.Set("X-Forwarded-For", "1.1.1.1")
  1814. v, err := s.maybeAuthenticate(r)
  1815. require.Nil(t, err)
  1816. require.Equal(t, "1.1.1.1", v.ip.String())
  1817. }
  1818. func TestServer_Visitor_XForwardedFor_Multiple(t *testing.T) {
  1819. c := newTestConfig(t)
  1820. c.BehindProxy = true
  1821. s := newTestServer(t, c)
  1822. r, _ := http.NewRequest("GET", "/bla", nil)
  1823. r.RemoteAddr = "8.9.10.11"
  1824. r.Header.Set("X-Forwarded-For", "1.2.3.4 , 2.4.4.2,234.5.2.1 ")
  1825. v, err := s.maybeAuthenticate(r)
  1826. require.Nil(t, err)
  1827. require.Equal(t, "234.5.2.1", v.ip.String())
  1828. }
  1829. func TestServer_PublishWhileUpdatingStatsWithLotsOfMessages(t *testing.T) {
  1830. t.Parallel()
  1831. count := 50000
  1832. c := newTestConfig(t)
  1833. c.TotalTopicLimit = 50001
  1834. c.CacheStartupQueries = "pragma journal_mode = WAL; pragma synchronous = normal; pragma temp_store = memory;"
  1835. s := newTestServer(t, c)
  1836. // Add lots of messages
  1837. log.Info("Adding %d messages", count)
  1838. start := time.Now()
  1839. messages := make([]*message, 0)
  1840. for i := 0; i < count; i++ {
  1841. topicID := fmt.Sprintf("topic%d", i)
  1842. _, err := s.topicsFromIDs(topicID) // Add topic to internal s.topics array
  1843. require.Nil(t, err)
  1844. messages = append(messages, newDefaultMessage(topicID, "some message"))
  1845. }
  1846. require.Nil(t, s.messageCache.addMessages(messages))
  1847. log.Info("Done: Adding %d messages; took %s", count, time.Since(start).Round(time.Millisecond))
  1848. // Update stats
  1849. statsChan := make(chan bool)
  1850. go func() {
  1851. log.Info("Updating stats")
  1852. start := time.Now()
  1853. s.execManager()
  1854. log.Info("Done: Updating stats; took %s", time.Since(start).Round(time.Millisecond))
  1855. statsChan <- true
  1856. }()
  1857. time.Sleep(50 * time.Millisecond) // Make sure it starts first
  1858. // Publish message (during stats update)
  1859. log.Info("Publishing message")
  1860. start = time.Now()
  1861. response := request(t, s, "PUT", "/mytopic", "some body", nil)
  1862. m := toMessage(t, response.Body.String())
  1863. require.Equal(t, "some body", m.Message)
  1864. require.True(t, time.Since(start) < 100*time.Millisecond)
  1865. log.Info("Done: Publishing message; took %s", time.Since(start).Round(time.Millisecond))
  1866. // Wait for all goroutines
  1867. select {
  1868. case <-statsChan:
  1869. case <-time.After(10 * time.Second):
  1870. t.Fatal("Timed out waiting for Go routines")
  1871. }
  1872. log.Info("Done: Waiting for all locks")
  1873. }
  1874. func TestServer_AnonymousUser_And_NonTierUser_Are_Same_Visitor(t *testing.T) {
  1875. conf := newTestConfigWithAuthFile(t)
  1876. s := newTestServer(t, conf)
  1877. defer s.closeDatabases()
  1878. // Create user without tier
  1879. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser))
  1880. // Publish a message (anonymous user)
  1881. rr := request(t, s, "POST", "/mytopic", "hi", nil)
  1882. require.Equal(t, 200, rr.Code)
  1883. // Publish a message (non-tier user)
  1884. rr = request(t, s, "POST", "/mytopic", "hi", map[string]string{
  1885. "Authorization": util.BasicAuth("phil", "phil"),
  1886. })
  1887. require.Equal(t, 200, rr.Code)
  1888. // User stats (anonymous user)
  1889. rr = request(t, s, "GET", "/v1/account", "", nil)
  1890. account, _ := util.UnmarshalJSON[apiAccountResponse](io.NopCloser(rr.Body))
  1891. require.Equal(t, int64(2), account.Stats.Messages)
  1892. // User stats (non-tier user)
  1893. rr = request(t, s, "GET", "/v1/account", "", map[string]string{
  1894. "Authorization": util.BasicAuth("phil", "phil"),
  1895. })
  1896. account, _ = util.UnmarshalJSON[apiAccountResponse](io.NopCloser(rr.Body))
  1897. require.Equal(t, int64(2), account.Stats.Messages)
  1898. }
  1899. func TestServer_SubscriberRateLimiting_Success(t *testing.T) {
  1900. c := newTestConfigWithAuthFile(t)
  1901. c.VisitorRequestLimitBurst = 3
  1902. c.VisitorSubscriberRateLimiting = true
  1903. s := newTestServer(t, c)
  1904. // "Register" visitor 1.2.3.4 to topic "upAAAAAAAAAAAA" as a rate limit visitor
  1905. subscriber1Fn := func(r *http.Request) {
  1906. r.RemoteAddr = "1.2.3.4"
  1907. }
  1908. rr := request(t, s, "GET", "/upAAAAAAAAAAAA/json?poll=1", "", nil, subscriber1Fn)
  1909. require.Equal(t, 200, rr.Code)
  1910. require.Equal(t, "", rr.Body.String())
  1911. require.Equal(t, "1.2.3.4", s.topics["upAAAAAAAAAAAA"].rateVisitor.ip.String())
  1912. // "Register" visitor 8.7.7.1 to topic "up012345678912" as a rate limit visitor (implicitly via topic name)
  1913. subscriber2Fn := func(r *http.Request) {
  1914. r.RemoteAddr = "8.7.7.1"
  1915. }
  1916. rr = request(t, s, "GET", "/up012345678912/json?poll=1", "", nil, subscriber2Fn)
  1917. require.Equal(t, 200, rr.Code)
  1918. require.Equal(t, "", rr.Body.String())
  1919. require.Equal(t, "8.7.7.1", s.topics["up012345678912"].rateVisitor.ip.String())
  1920. // Publish 2 messages to "subscriber1topic" as visitor 9.9.9.9. It'd be 3 normally, but the
  1921. // GET request before is also counted towards the request limiter.
  1922. for i := 0; i < 2; i++ {
  1923. rr := request(t, s, "PUT", "/upAAAAAAAAAAAA", "some message", nil)
  1924. require.Equal(t, 200, rr.Code)
  1925. }
  1926. rr = request(t, s, "PUT", "/upAAAAAAAAAAAA", "some message", nil)
  1927. require.Equal(t, 429, rr.Code)
  1928. // Publish another 2 messages to "up012345678912" as visitor 9.9.9.9
  1929. for i := 0; i < 2; i++ {
  1930. rr := request(t, s, "PUT", "/up012345678912", "some message", nil)
  1931. require.Equal(t, 200, rr.Code) // If we fail here, handlePublish is using the wrong visitor!
  1932. }
  1933. rr = request(t, s, "PUT", "/up012345678912", "some message", nil)
  1934. require.Equal(t, 429, rr.Code)
  1935. // Hurray! At this point, visitor 9.9.9.9 has published 4 messages, even though
  1936. // VisitorRequestLimitBurst is 3. That means it's working.
  1937. // Now let's confirm that so far we haven't used up any of visitor 9.9.9.9's request limiter
  1938. // by publishing another 3 requests from it.
  1939. for i := 0; i < 3; i++ {
  1940. rr := request(t, s, "PUT", "/some-other-topic", "some message", nil)
  1941. require.Equal(t, 200, rr.Code)
  1942. }
  1943. rr = request(t, s, "PUT", "/some-other-topic", "some message", nil)
  1944. require.Equal(t, 429, rr.Code)
  1945. }
  1946. func TestServer_SubscriberRateLimiting_NotEnabled_Failed(t *testing.T) {
  1947. c := newTestConfigWithAuthFile(t)
  1948. c.VisitorRequestLimitBurst = 3
  1949. c.VisitorSubscriberRateLimiting = false
  1950. s := newTestServer(t, c)
  1951. // Subscriber rate limiting is disabled!
  1952. // Registering visitor 1.2.3.4 to topic has no effect
  1953. rr := request(t, s, "GET", "/upAAAAAAAAAAAA/json?poll=1", "", nil, func(r *http.Request) {
  1954. r.RemoteAddr = "1.2.3.4"
  1955. })
  1956. require.Equal(t, 200, rr.Code)
  1957. require.Equal(t, "", rr.Body.String())
  1958. require.Nil(t, s.topics["upAAAAAAAAAAAA"].rateVisitor)
  1959. // Registering visitor 8.7.7.1 to topic has no effect
  1960. rr = request(t, s, "GET", "/up012345678912/json?poll=1", "", nil, func(r *http.Request) {
  1961. r.RemoteAddr = "8.7.7.1"
  1962. })
  1963. require.Equal(t, 200, rr.Code)
  1964. require.Equal(t, "", rr.Body.String())
  1965. require.Nil(t, s.topics["up012345678912"].rateVisitor)
  1966. // Publish 3 messages to "upAAAAAAAAAAAA" as visitor 9.9.9.9
  1967. for i := 0; i < 3; i++ {
  1968. rr := request(t, s, "PUT", "/subscriber1topic", "some message", nil)
  1969. require.Equal(t, 200, rr.Code)
  1970. }
  1971. rr = request(t, s, "PUT", "/subscriber1topic", "some message", nil)
  1972. require.Equal(t, 429, rr.Code)
  1973. rr = request(t, s, "PUT", "/up012345678912", "some message", nil)
  1974. require.Equal(t, 429, rr.Code)
  1975. }
  1976. func TestServer_SubscriberRateLimiting_UP_Only(t *testing.T) {
  1977. c := newTestConfigWithAuthFile(t)
  1978. c.VisitorRequestLimitBurst = 3
  1979. c.VisitorSubscriberRateLimiting = true
  1980. s := newTestServer(t, c)
  1981. // "Register" 5 different UnifiedPush visitors
  1982. for i := 0; i < 5; i++ {
  1983. subscriberFn := func(r *http.Request) {
  1984. r.RemoteAddr = fmt.Sprintf("1.2.3.%d", i+1)
  1985. }
  1986. rr := request(t, s, "GET", fmt.Sprintf("/up12345678901%d/json?poll=1", i), "", nil, subscriberFn)
  1987. require.Equal(t, 200, rr.Code)
  1988. }
  1989. // Publish 2 messages per topic
  1990. for i := 0; i < 5; i++ {
  1991. for j := 0; j < 2; j++ {
  1992. rr := request(t, s, "PUT", fmt.Sprintf("/up12345678901%d?up=1", i), "some message", nil)
  1993. require.Equal(t, 200, rr.Code)
  1994. }
  1995. }
  1996. }
  1997. func TestServer_Matrix_SubscriberRateLimiting_UP_Only(t *testing.T) {
  1998. c := newTestConfig(t)
  1999. c.VisitorRequestLimitBurst = 3
  2000. c.VisitorSubscriberRateLimiting = true
  2001. s := newTestServer(t, c)
  2002. // "Register" 5 different UnifiedPush visitors
  2003. for i := 0; i < 5; i++ {
  2004. rr := request(t, s, "GET", fmt.Sprintf("/up12345678901%d/json?poll=1", i), "", nil, func(r *http.Request) {
  2005. r.RemoteAddr = fmt.Sprintf("1.2.3.%d", i+1)
  2006. })
  2007. require.Equal(t, 200, rr.Code)
  2008. }
  2009. // Publish 2 messages per topic
  2010. for i := 0; i < 5; i++ {
  2011. notification := fmt.Sprintf(`{"notification":{"devices":[{"pushkey":"http://127.0.0.1:12345/up12345678901%d?up=1"}]}}`, i)
  2012. for j := 0; j < 2; j++ {
  2013. response := request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  2014. require.Equal(t, 200, response.Code)
  2015. require.Equal(t, `{"rejected":[]}`+"\n", response.Body.String())
  2016. }
  2017. response := request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  2018. require.Equal(t, 429, response.Code, notification)
  2019. require.Equal(t, 42901, toHTTPError(t, response.Body.String()).Code)
  2020. }
  2021. }
  2022. func TestServer_SubscriberRateLimiting_VisitorExpiration(t *testing.T) {
  2023. c := newTestConfig(t)
  2024. c.VisitorRequestLimitBurst = 3
  2025. c.VisitorSubscriberRateLimiting = true
  2026. s := newTestServer(t, c)
  2027. // "Register" rate visitor
  2028. subscriberFn := func(r *http.Request) {
  2029. r.RemoteAddr = "1.2.3.4"
  2030. }
  2031. rr := request(t, s, "GET", "/upAAAAAAAAAAAA/json?poll=1", "", nil, subscriberFn)
  2032. require.Equal(t, 200, rr.Code)
  2033. require.Equal(t, "1.2.3.4", s.topics["upAAAAAAAAAAAA"].rateVisitor.ip.String())
  2034. require.Equal(t, s.visitors["ip:1.2.3.4"], s.topics["upAAAAAAAAAAAA"].rateVisitor)
  2035. // Publish message, observe rate visitor tokens being decreased
  2036. response := request(t, s, "POST", "/upAAAAAAAAAAAA", "some message", nil)
  2037. require.Equal(t, 200, response.Code)
  2038. require.Equal(t, int64(0), s.visitors["ip:9.9.9.9"].messagesLimiter.Value())
  2039. require.Equal(t, int64(1), s.topics["upAAAAAAAAAAAA"].rateVisitor.messagesLimiter.Value())
  2040. require.Equal(t, s.visitors["ip:1.2.3.4"], s.topics["upAAAAAAAAAAAA"].rateVisitor)
  2041. // Expire visitor
  2042. s.visitors["ip:1.2.3.4"].seen = time.Now().Add(-1 * 25 * time.Hour)
  2043. s.pruneVisitors()
  2044. // Publish message again, observe that rateVisitor is not used anymore and is reset
  2045. response = request(t, s, "POST", "/upAAAAAAAAAAAA", "some message", nil)
  2046. require.Equal(t, 200, response.Code)
  2047. require.Equal(t, int64(1), s.visitors["ip:9.9.9.9"].messagesLimiter.Value())
  2048. require.Nil(t, s.topics["upAAAAAAAAAAAA"].rateVisitor)
  2049. require.Nil(t, s.visitors["ip:1.2.3.4"])
  2050. }
  2051. func TestServer_SubscriberRateLimiting_ProtectedTopics_WithDefaultReadWrite(t *testing.T) {
  2052. c := newTestConfigWithAuthFile(t)
  2053. c.AuthDefault = user.PermissionReadWrite
  2054. c.VisitorSubscriberRateLimiting = true
  2055. s := newTestServer(t, c)
  2056. // Create some ACLs
  2057. require.Nil(t, s.userManager.AllowAccess(user.Everyone, "announcements", user.PermissionRead))
  2058. // Set rate visitor as ip:1.2.3.4 on topic
  2059. // - "up123456789012": Allowed, because no ACLs and nobody owns the topic
  2060. // - "announcements": NOT allowed, because it has read-only permissions for everyone
  2061. rr := request(t, s, "GET", "/up123456789012,announcements/json?poll=1", "", nil, func(r *http.Request) {
  2062. r.RemoteAddr = "1.2.3.4"
  2063. })
  2064. require.Equal(t, 200, rr.Code)
  2065. require.Equal(t, "1.2.3.4", s.topics["up123456789012"].rateVisitor.ip.String())
  2066. require.Nil(t, s.topics["announcements"].rateVisitor)
  2067. }
  2068. func TestServer_MessageHistoryAndStatsEndpoint(t *testing.T) {
  2069. c := newTestConfig(t)
  2070. c.ManagerInterval = 2 * time.Second
  2071. s := newTestServer(t, c)
  2072. // Publish some messages, and get stats
  2073. for i := 0; i < 5; i++ {
  2074. response := request(t, s, "POST", "/mytopic", "some message", nil)
  2075. require.Equal(t, 200, response.Code)
  2076. }
  2077. require.Equal(t, int64(5), s.messages)
  2078. require.Equal(t, []int64{0}, s.messagesHistory)
  2079. response := request(t, s, "GET", "/v1/stats", "", nil)
  2080. require.Equal(t, 200, response.Code)
  2081. require.Equal(t, `{"messages":5,"messages_rate":0}`+"\n", response.Body.String())
  2082. // Run manager and see message history update
  2083. s.execManager()
  2084. require.Equal(t, []int64{0, 5}, s.messagesHistory)
  2085. response = request(t, s, "GET", "/v1/stats", "", nil)
  2086. require.Equal(t, 200, response.Code)
  2087. require.Equal(t, `{"messages":5,"messages_rate":2.5}`+"\n", response.Body.String()) // 5 messages in 2 seconds = 2.5 messages per second
  2088. // Publish some more messages
  2089. for i := 0; i < 10; i++ {
  2090. response := request(t, s, "POST", "/mytopic", "some message", nil)
  2091. require.Equal(t, 200, response.Code)
  2092. }
  2093. require.Equal(t, int64(15), s.messages)
  2094. require.Equal(t, []int64{0, 5}, s.messagesHistory)
  2095. response = request(t, s, "GET", "/v1/stats", "", nil)
  2096. require.Equal(t, 200, response.Code)
  2097. require.Equal(t, `{"messages":15,"messages_rate":2.5}`+"\n", response.Body.String()) // Rate did not update yet
  2098. // Run manager and see message history update
  2099. s.execManager()
  2100. require.Equal(t, []int64{0, 5, 15}, s.messagesHistory)
  2101. response = request(t, s, "GET", "/v1/stats", "", nil)
  2102. require.Equal(t, 200, response.Code)
  2103. require.Equal(t, `{"messages":15,"messages_rate":3.75}`+"\n", response.Body.String()) // 15 messages in 4 seconds = 3.75 messages per second
  2104. }
  2105. func TestServer_MessageHistoryMaxSize(t *testing.T) {
  2106. t.Parallel()
  2107. s := newTestServer(t, newTestConfig(t))
  2108. for i := 0; i < 20; i++ {
  2109. s.messages = int64(i)
  2110. s.execManager()
  2111. }
  2112. require.Equal(t, []int64{10, 11, 12, 13, 14, 15, 16, 17, 18, 19}, s.messagesHistory)
  2113. }
  2114. func TestServer_MessageCountPersistence(t *testing.T) {
  2115. t.Parallel()
  2116. c := newTestConfig(t)
  2117. s := newTestServer(t, c)
  2118. s.messages = 1234
  2119. s.execManager()
  2120. waitFor(t, func() bool {
  2121. messages, err := s.messageCache.Stats()
  2122. require.Nil(t, err)
  2123. return messages == 1234
  2124. })
  2125. s = newTestServer(t, c)
  2126. require.Equal(t, int64(1234), s.messages)
  2127. }
  2128. func TestServer_PublishWithUTF8MimeHeader(t *testing.T) {
  2129. t.Parallel()
  2130. s := newTestServer(t, newTestConfig(t))
  2131. response := request(t, s, "POST", "/mytopic", "some attachment", map[string]string{
  2132. "X-Filename": "some =?UTF-8?q?=C3=A4?=ttachment.txt",
  2133. "X-Message": "=?UTF-8?B?8J+HqfCfh6o=?=",
  2134. "X-Title": "=?UTF-8?B?bnRmeSDlvojmo5I=?=, no really I mean it! =?UTF-8?Q?This is q=C3=BC=C3=B6ted-print=C3=A4ble.?=",
  2135. "X-Tags": "=?UTF-8?B?8J+HqfCfh6o=?=, =?UTF-8?B?bnRmeSDlvojmo5I=?=",
  2136. "X-Click": "=?uTf-8?b?aHR0cHM6Ly/wn5KpLmxh?=",
  2137. "X-Actions": "http, \"=?utf-8?q?Mettre =C3=A0 jour?=\", \"https://my.tld/webhook/netbird-update\"; =?utf-8?b?aHR0cCwg6L+Z5piv5LiA5Liq5qCH562+LCBodHRwczovL/CfkqkubGE=?=",
  2138. })
  2139. require.Equal(t, 200, response.Code)
  2140. m := toMessage(t, response.Body.String())
  2141. require.Equal(t, "🇩🇪", m.Message)
  2142. require.Equal(t, "ntfy 很棒, no really I mean it! This is qüöted-printäble.", m.Title)
  2143. require.Equal(t, "some ättachment.txt", m.Attachment.Name)
  2144. require.Equal(t, "🇩🇪", m.Tags[0])
  2145. require.Equal(t, "ntfy 很棒", m.Tags[1])
  2146. require.Equal(t, "https://💩.la", m.Click)
  2147. require.Equal(t, "Mettre à jour", m.Actions[0].Label)
  2148. require.Equal(t, "http", m.Actions[1].Action)
  2149. require.Equal(t, "这是一个标签", m.Actions[1].Label)
  2150. require.Equal(t, "https://💩.la", m.Actions[1].URL)
  2151. }
  2152. func TestServer_UpstreamBaseURL_Success(t *testing.T) {
  2153. t.Parallel()
  2154. var pollID atomic.Pointer[string]
  2155. upstreamServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  2156. body, err := io.ReadAll(r.Body)
  2157. require.Nil(t, err)
  2158. require.Equal(t, "/87c9cddf7b0105f5fe849bf084c6e600be0fde99be3223335199b4965bd7b735", r.URL.Path)
  2159. require.Equal(t, "", string(body))
  2160. require.NotEmpty(t, r.Header.Get("X-Poll-ID"))
  2161. pollID.Store(util.String(r.Header.Get("X-Poll-ID")))
  2162. }))
  2163. defer upstreamServer.Close()
  2164. c := newTestConfigWithAuthFile(t)
  2165. c.BaseURL = "http://myserver.internal"
  2166. c.UpstreamBaseURL = upstreamServer.URL
  2167. s := newTestServer(t, c)
  2168. // Send message, and wait for upstream server to receive it
  2169. response := request(t, s, "PUT", "/mytopic", `hi there`, nil)
  2170. require.Equal(t, 200, response.Code)
  2171. m := toMessage(t, response.Body.String())
  2172. require.NotEmpty(t, m.ID)
  2173. require.Equal(t, "hi there", m.Message)
  2174. waitFor(t, func() bool {
  2175. pID := pollID.Load()
  2176. return pID != nil && *pID == m.ID
  2177. })
  2178. }
  2179. func TestServer_UpstreamBaseURL_With_Access_Token_Success(t *testing.T) {
  2180. t.Parallel()
  2181. var pollID atomic.Pointer[string]
  2182. upstreamServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  2183. body, err := io.ReadAll(r.Body)
  2184. require.Nil(t, err)
  2185. require.Equal(t, "/a1c72bcb4daf5af54d13ef86aea8f76c11e8b88320d55f1811d5d7b173bcc1df", r.URL.Path)
  2186. require.Equal(t, "Bearer tk_1234567890", r.Header.Get("Authorization"))
  2187. require.Equal(t, "", string(body))
  2188. require.NotEmpty(t, r.Header.Get("X-Poll-ID"))
  2189. pollID.Store(util.String(r.Header.Get("X-Poll-ID")))
  2190. }))
  2191. defer upstreamServer.Close()
  2192. c := newTestConfigWithAuthFile(t)
  2193. c.BaseURL = "http://myserver.internal"
  2194. c.UpstreamBaseURL = upstreamServer.URL
  2195. c.UpstreamAccessToken = "tk_1234567890"
  2196. s := newTestServer(t, c)
  2197. // Send message, and wait for upstream server to receive it
  2198. response := request(t, s, "PUT", "/mytopic1", `hi there`, nil)
  2199. require.Equal(t, 200, response.Code)
  2200. m := toMessage(t, response.Body.String())
  2201. require.NotEmpty(t, m.ID)
  2202. require.Equal(t, "hi there", m.Message)
  2203. waitFor(t, func() bool {
  2204. pID := pollID.Load()
  2205. return pID != nil && *pID == m.ID
  2206. })
  2207. }
  2208. func TestServer_UpstreamBaseURL_DoNotForwardUnifiedPush(t *testing.T) {
  2209. t.Parallel()
  2210. upstreamServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  2211. t.Fatal("UnifiedPush messages should not be forwarded")
  2212. }))
  2213. defer upstreamServer.Close()
  2214. c := newTestConfigWithAuthFile(t)
  2215. c.BaseURL = "http://myserver.internal"
  2216. c.UpstreamBaseURL = upstreamServer.URL
  2217. s := newTestServer(t, c)
  2218. // Send UP message, this should not forward to upstream server
  2219. response := request(t, s, "PUT", "/mytopic?up=1", `hi there`, nil)
  2220. require.Equal(t, 200, response.Code)
  2221. m := toMessage(t, response.Body.String())
  2222. require.NotEmpty(t, m.ID)
  2223. require.Equal(t, "hi there", m.Message)
  2224. // Forwarding is done asynchronously, so wait a bit.
  2225. // This ensures that the t.Fatal above is actually not triggered.
  2226. time.Sleep(500 * time.Millisecond)
  2227. }
  2228. func TestServer_MessageTemplate(t *testing.T) {
  2229. t.Parallel()
  2230. s := newTestServer(t, newTestConfig(t))
  2231. response := request(t, s, "PUT", "/mytopic", `{"foo":"bar", "nested":{"title":"here"}}`, map[string]string{
  2232. "X-Message": "{{.foo}}",
  2233. "X-Title": "{{.nested.title}}",
  2234. "X-Template": "1",
  2235. })
  2236. require.Equal(t, 200, response.Code)
  2237. m := toMessage(t, response.Body.String())
  2238. require.Equal(t, "bar", m.Message)
  2239. require.Equal(t, "here", m.Title)
  2240. }
  2241. func TestServer_MessageTemplate_RepeatPlaceholder(t *testing.T) {
  2242. t.Parallel()
  2243. s := newTestServer(t, newTestConfig(t))
  2244. response := request(t, s, "PUT", "/mytopic", `{"foo":"bar", "nested":{"title":"here"}}`, map[string]string{
  2245. "Message": "{{.foo}} is {{.foo}}",
  2246. "Title": "{{.nested.title}} is {{.nested.title}}",
  2247. "Template": "1",
  2248. })
  2249. require.Equal(t, 200, response.Code)
  2250. m := toMessage(t, response.Body.String())
  2251. require.Equal(t, "bar is bar", m.Message)
  2252. require.Equal(t, "here is here", m.Title)
  2253. }
  2254. func TestServer_MessageTemplate_JSONBody(t *testing.T) {
  2255. t.Parallel()
  2256. s := newTestServer(t, newTestConfig(t))
  2257. body := `{"topic": "mytopic", "message": "{\"foo\":\"bar\",\"nested\":{\"title\":\"here\"}}"}`
  2258. response := request(t, s, "PUT", "/", body, map[string]string{
  2259. "m": "{{.foo}}",
  2260. "t": "{{.nested.title}}",
  2261. "tpl": "1",
  2262. })
  2263. require.Equal(t, 200, response.Code)
  2264. m := toMessage(t, response.Body.String())
  2265. require.Equal(t, "bar", m.Message)
  2266. require.Equal(t, "here", m.Title)
  2267. }
  2268. func TestServer_MessageTemplate_MalformedJSONBody(t *testing.T) {
  2269. t.Parallel()
  2270. s := newTestServer(t, newTestConfig(t))
  2271. body := `{"topic": "mytopic", "message": "{\"foo\":\"bar\",\"nested\":{\"title\":\"here\"INVALID"}`
  2272. response := request(t, s, "PUT", "/", body, map[string]string{
  2273. "X-Message": "{{.foo}}",
  2274. "X-Title": "{{.nested.title}}",
  2275. "X-Template": "1",
  2276. })
  2277. require.Equal(t, 400, response.Code)
  2278. require.Equal(t, 40042, toHTTPError(t, response.Body.String()).Code)
  2279. }
  2280. func TestServer_MessageTemplate_PlaceholderTypo(t *testing.T) {
  2281. t.Parallel()
  2282. s := newTestServer(t, newTestConfig(t))
  2283. response := request(t, s, "PUT", "/mytopic", `{"foo":"bar", "nested":{"title":"here"}}`, map[string]string{
  2284. "X-Message": "{{.food}}",
  2285. "X-Title": "{{.neste.title}}",
  2286. "X-Template": "1",
  2287. })
  2288. require.Equal(t, 200, response.Code)
  2289. m := toMessage(t, response.Body.String())
  2290. require.Equal(t, "<no value>", m.Message)
  2291. require.Equal(t, "<no value>", m.Title)
  2292. }
  2293. func TestServer_MessageTemplate_MultiplePlaceholders(t *testing.T) {
  2294. t.Parallel()
  2295. s := newTestServer(t, newTestConfig(t))
  2296. response := request(t, s, "PUT", "/mytopic", `{"foo":"bar", "nested":{"title":"here"}}`, map[string]string{
  2297. "X-Message": "{{.foo}} is {{.nested.title}}",
  2298. "X-Template": "1",
  2299. })
  2300. require.Equal(t, 200, response.Code)
  2301. m := toMessage(t, response.Body.String())
  2302. require.Equal(t, "bar is here", m.Message)
  2303. }
  2304. func TestServer_MessageTemplate_Range(t *testing.T) {
  2305. t.Parallel()
  2306. s := newTestServer(t, newTestConfig(t))
  2307. jsonBody := `{"foo": "bar", "errors": [{"level": "severe", "url": "https://severe1.com"},{"level": "warning", "url": "https://warning.com"},{"level": "severe", "url": "https://severe2.com"}]}`
  2308. response := request(t, s, "PUT", "/mytopic", jsonBody, map[string]string{
  2309. "X-Message": `Severe URLs:\n{{range .errors}}{{if eq .level "severe"}}- {{.url}}\n{{end}}{{end}}`,
  2310. "X-Template": "1",
  2311. })
  2312. require.Equal(t, 200, response.Code)
  2313. m := toMessage(t, response.Body.String())
  2314. require.Equal(t, "Severe URLs:\n- https://severe1.com\n- https://severe2.com\n", m.Message)
  2315. }
  2316. func TestServer_MessageTemplate_ExceedMessageSize_TemplatedMessageOK(t *testing.T) {
  2317. t.Parallel()
  2318. c := newTestConfig(t)
  2319. c.MessageSizeLimit = 25 // 25 < len(HTTP body) < 32k, and len(m.Message) < 25
  2320. s := newTestServer(t, c)
  2321. response := request(t, s, "PUT", "/mytopic", `{"foo":"bar", "nested":{"title":"here"}}`, map[string]string{
  2322. "X-Message": "{{.foo}}",
  2323. "X-Title": "{{.nested.title}}",
  2324. "X-Template": "yes",
  2325. })
  2326. require.Equal(t, 200, response.Code)
  2327. m := toMessage(t, response.Body.String())
  2328. require.Equal(t, "bar", m.Message)
  2329. require.Equal(t, "here", m.Title)
  2330. }
  2331. func TestServer_MessageTemplate_ExceedMessageSize_TemplatedMessageTooLong(t *testing.T) {
  2332. t.Parallel()
  2333. c := newTestConfig(t)
  2334. c.MessageSizeLimit = 21 // 21 < len(HTTP body) < 32k, but !len(m.Message) < 21
  2335. s := newTestServer(t, c)
  2336. response := request(t, s, "PUT", "/mytopic", `{"foo":"This is a long message"}`, map[string]string{
  2337. "X-Message": "{{.foo}}",
  2338. "X-Template": "1",
  2339. })
  2340. require.Equal(t, 400, response.Code)
  2341. require.Equal(t, 40041, toHTTPError(t, response.Body.String()).Code)
  2342. }
  2343. func TestServer_MessageTemplate_Grafana(t *testing.T) {
  2344. t.Parallel()
  2345. c := newTestConfig(t)
  2346. s := newTestServer(t, c)
  2347. 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"}`
  2348. response := request(t, s, "PUT", "/mytopic?tpl=yes&title=Grafana+alert:+{{.title}}&message={{.message}}", body, nil)
  2349. require.Equal(t, 200, response.Code)
  2350. m := toMessage(t, response.Body.String())
  2351. require.Equal(t, "Grafana alert: [RESOLVED] Load avg 15m too high Node alerts (10.108.0.2:9100 node-exporter)", m.Title)
  2352. require.Equal(t, `**Resolved**
  2353. Value: B=18.98211314475876, C=0
  2354. Labels:
  2355. - alertname = Load avg 15m too high
  2356. - grafana_folder = Node alerts
  2357. - instance = 10.108.0.2:9100
  2358. - job = node-exporter
  2359. Annotations:
  2360. - summary = 15m load average too high
  2361. Source: localhost:3000/alerting/grafana/NW9oDw-4z/view
  2362. 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
  2363. `, m.Message)
  2364. }
  2365. func TestServer_MessageTemplate_GitHub(t *testing.T) {
  2366. t.Parallel()
  2367. c := newTestConfig(t)
  2368. s := newTestServer(t, c)
  2369. 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}}`
  2370. 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)
  2371. require.Equal(t, 200, response.Code)
  2372. m := toMessage(t, response.Body.String())
  2373. require.Equal(t, "", m.Title)
  2374. require.Equal(t, `[binwiederhier/dabble] Pull request OPENED: A sample PR from Phil`, m.Message)
  2375. }
  2376. func TestServer_MessageTemplate_GitHub2(t *testing.T) {
  2377. t.Parallel()
  2378. c := newTestConfig(t)
  2379. s := newTestServer(t, c)
  2380. 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}}`
  2381. 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)
  2382. require.Equal(t, 200, response.Code)
  2383. m := toMessage(t, response.Body.String())
  2384. require.Equal(t, `New PR: #1 by binwiederhier`, m.Title)
  2385. require.Equal(t, `A sample PR from Phil in binwiederhier/dabble. View more at https://github.com/binwiederhier/dabble/pull/1`, m.Message)
  2386. }
  2387. func newTestConfig(t *testing.T) *Config {
  2388. conf := NewConfig()
  2389. conf.BaseURL = "http://127.0.0.1:12345"
  2390. conf.CacheFile = filepath.Join(t.TempDir(), "cache.db")
  2391. conf.CacheStartupQueries = "pragma journal_mode = WAL; pragma synchronous = normal; pragma temp_store = memory;"
  2392. conf.AttachmentCacheDir = t.TempDir()
  2393. return conf
  2394. }
  2395. func configureAuth(t *testing.T, conf *Config) *Config {
  2396. conf.AuthFile = filepath.Join(t.TempDir(), "user.db")
  2397. conf.AuthStartupQueries = "pragma journal_mode = WAL; pragma synchronous = normal; pragma temp_store = memory;"
  2398. conf.AuthBcryptCost = bcrypt.MinCost // This speeds up tests a lot
  2399. return conf
  2400. }
  2401. func newTestConfigWithAuthFile(t *testing.T) *Config {
  2402. conf := newTestConfig(t)
  2403. conf = configureAuth(t, conf)
  2404. return conf
  2405. }
  2406. func newTestConfigWithWebPush(t *testing.T) *Config {
  2407. conf := newTestConfig(t)
  2408. privateKey, publicKey, err := webpush.GenerateVAPIDKeys()
  2409. require.Nil(t, err)
  2410. conf.WebPushFile = filepath.Join(t.TempDir(), "webpush.db")
  2411. conf.WebPushEmailAddress = "testing@example.com"
  2412. conf.WebPushPrivateKey = privateKey
  2413. conf.WebPushPublicKey = publicKey
  2414. return conf
  2415. }
  2416. func newTestServer(t *testing.T, config *Config) *Server {
  2417. server, err := New(config)
  2418. require.Nil(t, err)
  2419. return server
  2420. }
  2421. func request(t *testing.T, s *Server, method, url, body string, headers map[string]string, fn ...func(r *http.Request)) *httptest.ResponseRecorder {
  2422. rr := httptest.NewRecorder()
  2423. r, err := http.NewRequest(method, url, strings.NewReader(body))
  2424. if err != nil {
  2425. t.Fatal(err)
  2426. }
  2427. r.RemoteAddr = "9.9.9.9" // Used for tests
  2428. for k, v := range headers {
  2429. r.Header.Set(k, v)
  2430. }
  2431. for _, f := range fn {
  2432. f(r)
  2433. }
  2434. s.handle(rr, r)
  2435. return rr
  2436. }
  2437. func subscribe(t *testing.T, s *Server, url string, rr *httptest.ResponseRecorder) context.CancelFunc {
  2438. ctx, cancel := context.WithCancel(context.Background())
  2439. req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
  2440. if err != nil {
  2441. t.Fatal(err)
  2442. }
  2443. done := make(chan bool)
  2444. go func() {
  2445. s.handle(rr, req)
  2446. done <- true
  2447. }()
  2448. cancelAndWaitForDone := func() {
  2449. time.Sleep(200 * time.Millisecond)
  2450. cancel()
  2451. <-done
  2452. }
  2453. time.Sleep(200 * time.Millisecond)
  2454. return cancelAndWaitForDone
  2455. }
  2456. func toMessages(t *testing.T, s string) []*message {
  2457. messages := make([]*message, 0)
  2458. scanner := bufio.NewScanner(strings.NewReader(s))
  2459. for scanner.Scan() {
  2460. messages = append(messages, toMessage(t, scanner.Text()))
  2461. }
  2462. return messages
  2463. }
  2464. func toMessage(t *testing.T, s string) *message {
  2465. var m message
  2466. require.Nil(t, json.NewDecoder(strings.NewReader(s)).Decode(&m))
  2467. return &m
  2468. }
  2469. func toHTTPError(t *testing.T, s string) *errHTTP {
  2470. var e errHTTP
  2471. require.Nil(t, json.NewDecoder(strings.NewReader(s)).Decode(&e))
  2472. return &e
  2473. }
  2474. func readAll(t *testing.T, rc io.ReadCloser) string {
  2475. b, err := io.ReadAll(rc)
  2476. if err != nil {
  2477. t.Fatal(err)
  2478. }
  2479. return string(b)
  2480. }
  2481. func waitFor(t *testing.T, f func() bool) {
  2482. waitForWithMaxWait(t, 5*time.Second, f)
  2483. }
  2484. func waitForWithMaxWait(t *testing.T, maxWait time.Duration, f func() bool) {
  2485. start := time.Now()
  2486. for time.Since(start) < maxWait {
  2487. if f() {
  2488. return
  2489. }
  2490. time.Sleep(50 * time.Millisecond)
  2491. }
  2492. t.Fatalf("Function f did not succeed after %v: %v", maxWait, string(debug.Stack()))
  2493. }