server_test.go 96 KB

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