server_test.go 152 KB

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