server_test.go 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691
  1. package server
  2. import (
  3. "bufio"
  4. "context"
  5. "encoding/base64"
  6. "encoding/json"
  7. "fmt"
  8. "heckel.io/ntfy/user"
  9. "io"
  10. "log"
  11. "math/rand"
  12. "net/http"
  13. "net/http/httptest"
  14. "net/netip"
  15. "path/filepath"
  16. "strings"
  17. "sync"
  18. "testing"
  19. "time"
  20. "github.com/stretchr/testify/assert"
  21. "github.com/stretchr/testify/require"
  22. "heckel.io/ntfy/util"
  23. )
  24. func TestServer_PublishAndPoll(t *testing.T) {
  25. s := newTestServer(t, newTestConfig(t))
  26. response1 := request(t, s, "PUT", "/mytopic", "my first message", nil)
  27. msg1 := toMessage(t, response1.Body.String())
  28. require.NotEmpty(t, msg1.ID)
  29. require.Equal(t, "my first message", msg1.Message)
  30. response2 := request(t, s, "PUT", "/mytopic", "my second\n\nmessage", nil)
  31. msg2 := toMessage(t, response2.Body.String())
  32. require.NotEqual(t, msg1.ID, msg2.ID)
  33. require.NotEmpty(t, msg2.ID)
  34. require.Equal(t, "my second\n\nmessage", msg2.Message)
  35. response := request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  36. messages := toMessages(t, response.Body.String())
  37. require.Equal(t, 2, len(messages))
  38. require.Equal(t, "my first message", messages[0].Message)
  39. require.Equal(t, "my second\n\nmessage", messages[1].Message)
  40. response = request(t, s, "GET", "/mytopic/sse?poll=1&since=all", "", nil)
  41. lines := strings.Split(strings.TrimSpace(response.Body.String()), "\n")
  42. require.Equal(t, 3, len(lines))
  43. require.Equal(t, "my first message", toMessage(t, strings.TrimPrefix(lines[0], "data: ")).Message)
  44. require.Equal(t, "", lines[1])
  45. require.Equal(t, "my second\n\nmessage", toMessage(t, strings.TrimPrefix(lines[2], "data: ")).Message)
  46. response = request(t, s, "GET", "/mytopic/raw?poll=1", "", nil)
  47. lines = strings.Split(strings.TrimSpace(response.Body.String()), "\n")
  48. require.Equal(t, 2, len(lines))
  49. require.Equal(t, "my first message", lines[0])
  50. require.Equal(t, "my second message", lines[1]) // \n -> " "
  51. }
  52. func TestServer_PublishWithFirebase(t *testing.T) {
  53. sender := newTestFirebaseSender(10)
  54. s := newTestServer(t, newTestConfig(t))
  55. s.firebaseClient = newFirebaseClient(sender, &testAuther{Allow: true})
  56. response := request(t, s, "PUT", "/mytopic", "my first message", nil)
  57. msg1 := toMessage(t, response.Body.String())
  58. require.NotEmpty(t, msg1.ID)
  59. require.Equal(t, "my first message", msg1.Message)
  60. time.Sleep(100 * time.Millisecond) // Firebase publishing happens
  61. require.Equal(t, 1, len(sender.Messages()))
  62. require.Equal(t, "my first message", sender.Messages()[0].Data["message"])
  63. require.Equal(t, "my first message", sender.Messages()[0].APNS.Payload.Aps.Alert.Body)
  64. require.Equal(t, "my first message", sender.Messages()[0].APNS.Payload.CustomData["message"])
  65. }
  66. func TestServer_SubscribeOpenAndKeepalive(t *testing.T) {
  67. c := newTestConfig(t)
  68. c.KeepaliveInterval = time.Second
  69. s := newTestServer(t, c)
  70. rr := httptest.NewRecorder()
  71. ctx, cancel := context.WithCancel(context.Background())
  72. req, err := http.NewRequestWithContext(ctx, "GET", "/mytopic/json", nil)
  73. if err != nil {
  74. t.Fatal(err)
  75. }
  76. doneChan := make(chan bool)
  77. go func() {
  78. s.handle(rr, req)
  79. doneChan <- true
  80. }()
  81. time.Sleep(1300 * time.Millisecond)
  82. cancel()
  83. <-doneChan
  84. messages := toMessages(t, rr.Body.String())
  85. require.Equal(t, 2, len(messages))
  86. require.Equal(t, openEvent, messages[0].Event)
  87. require.Equal(t, "mytopic", messages[0].Topic)
  88. require.Equal(t, "", messages[0].Message)
  89. require.Equal(t, "", messages[0].Title)
  90. require.Equal(t, 0, messages[0].Priority)
  91. require.Nil(t, messages[0].Tags)
  92. require.Equal(t, keepaliveEvent, messages[1].Event)
  93. require.Equal(t, "mytopic", messages[1].Topic)
  94. require.Equal(t, "", messages[1].Message)
  95. require.Equal(t, "", messages[1].Title)
  96. require.Equal(t, 0, messages[1].Priority)
  97. require.Nil(t, messages[1].Tags)
  98. }
  99. func TestServer_PublishAndSubscribe(t *testing.T) {
  100. s := newTestServer(t, newTestConfig(t))
  101. subscribeRR := httptest.NewRecorder()
  102. subscribeCancel := subscribe(t, s, "/mytopic/json", subscribeRR)
  103. publishFirstRR := request(t, s, "PUT", "/mytopic", "my first message", nil)
  104. require.Equal(t, 200, publishFirstRR.Code)
  105. publishSecondRR := request(t, s, "PUT", "/mytopic", "my other message", map[string]string{
  106. "Title": " This is a title ",
  107. "X-Tags": "tag1,tag 2, tag3",
  108. "p": "1",
  109. })
  110. require.Equal(t, 200, publishSecondRR.Code)
  111. subscribeCancel()
  112. messages := toMessages(t, subscribeRR.Body.String())
  113. require.Equal(t, 3, len(messages))
  114. require.Equal(t, openEvent, messages[0].Event)
  115. require.Equal(t, messageEvent, messages[1].Event)
  116. require.Equal(t, "mytopic", messages[1].Topic)
  117. require.Equal(t, "my first message", messages[1].Message)
  118. require.Equal(t, "", messages[1].Title)
  119. require.Equal(t, 0, messages[1].Priority)
  120. require.Nil(t, messages[1].Tags)
  121. require.Equal(t, messageEvent, messages[2].Event)
  122. require.Equal(t, "mytopic", messages[2].Topic)
  123. require.Equal(t, "my other message", messages[2].Message)
  124. require.Equal(t, "This is a title", messages[2].Title)
  125. require.Equal(t, 1, messages[2].Priority)
  126. require.Equal(t, []string{"tag1", "tag 2", "tag3"}, messages[2].Tags)
  127. }
  128. func TestServer_StaticSites(t *testing.T) {
  129. s := newTestServer(t, newTestConfig(t))
  130. rr := request(t, s, "GET", "/", "", nil)
  131. require.Equal(t, 200, rr.Code)
  132. require.Contains(t, rr.Body.String(), "</html>")
  133. rr = request(t, s, "HEAD", "/", "", nil)
  134. require.Equal(t, 200, rr.Code)
  135. rr = request(t, s, "OPTIONS", "/", "", nil)
  136. require.Equal(t, 200, rr.Code)
  137. rr = request(t, s, "GET", "/does-not-exist.txt", "", nil)
  138. require.Equal(t, 404, rr.Code)
  139. rr = request(t, s, "GET", "/mytopic", "", nil)
  140. require.Equal(t, 200, rr.Code)
  141. require.Contains(t, rr.Body.String(), `<meta name="robots" content="noindex, nofollow"/>`)
  142. rr = request(t, s, "GET", "/static/css/home.css", "", nil)
  143. require.Equal(t, 200, rr.Code)
  144. require.Contains(t, rr.Body.String(), `/* general styling */`)
  145. rr = request(t, s, "GET", "/docs", "", nil)
  146. require.Equal(t, 301, rr.Code)
  147. // Docs test removed, it was failing annoyingly.
  148. }
  149. func TestServer_WebEnabled(t *testing.T) {
  150. conf := newTestConfig(t)
  151. conf.EnableWeb = false
  152. s := newTestServer(t, conf)
  153. rr := request(t, s, "GET", "/", "", nil)
  154. require.Equal(t, 404, rr.Code)
  155. rr = request(t, s, "GET", "/config.js", "", nil)
  156. require.Equal(t, 404, rr.Code)
  157. rr = request(t, s, "GET", "/static/css/home.css", "", nil)
  158. require.Equal(t, 404, rr.Code)
  159. conf2 := newTestConfig(t)
  160. conf2.EnableWeb = true
  161. s2 := newTestServer(t, conf2)
  162. rr = request(t, s2, "GET", "/", "", nil)
  163. require.Equal(t, 200, rr.Code)
  164. rr = request(t, s2, "GET", "/config.js", "", nil)
  165. require.Equal(t, 200, rr.Code)
  166. rr = request(t, s2, "GET", "/static/css/home.css", "", nil)
  167. require.Equal(t, 200, rr.Code)
  168. }
  169. func TestServer_PublishLargeMessage(t *testing.T) {
  170. c := newTestConfig(t)
  171. c.AttachmentCacheDir = "" // Disable attachments
  172. s := newTestServer(t, c)
  173. body := strings.Repeat("this is a large message", 5000)
  174. response := request(t, s, "PUT", "/mytopic", body, nil)
  175. require.Equal(t, 400, response.Code)
  176. }
  177. func TestServer_PublishPriority(t *testing.T) {
  178. s := newTestServer(t, newTestConfig(t))
  179. for prio := 1; prio <= 5; prio++ {
  180. response := request(t, s, "GET", fmt.Sprintf("/mytopic/publish?priority=%d", prio), fmt.Sprintf("priority %d", prio), nil)
  181. msg := toMessage(t, response.Body.String())
  182. require.Equal(t, prio, msg.Priority)
  183. }
  184. response := request(t, s, "GET", "/mytopic/publish?priority=min", "test", nil)
  185. require.Equal(t, 1, toMessage(t, response.Body.String()).Priority)
  186. response = request(t, s, "GET", "/mytopic/send?priority=low", "test", nil)
  187. require.Equal(t, 2, toMessage(t, response.Body.String()).Priority)
  188. response = request(t, s, "GET", "/mytopic/send?priority=default", "test", nil)
  189. require.Equal(t, 3, toMessage(t, response.Body.String()).Priority)
  190. response = request(t, s, "GET", "/mytopic/send?priority=high", "test", nil)
  191. require.Equal(t, 4, toMessage(t, response.Body.String()).Priority)
  192. response = request(t, s, "GET", "/mytopic/send?priority=max", "test", nil)
  193. require.Equal(t, 5, toMessage(t, response.Body.String()).Priority)
  194. response = request(t, s, "GET", "/mytopic/trigger?priority=urgent", "test", nil)
  195. require.Equal(t, 5, toMessage(t, response.Body.String()).Priority)
  196. response = request(t, s, "GET", "/mytopic/trigger?priority=INVALID", "test", nil)
  197. require.Equal(t, 40007, toHTTPError(t, response.Body.String()).Code)
  198. }
  199. func TestServer_PublishGETOnlyOneTopic(t *testing.T) {
  200. // This tests a bug that allowed publishing topics with a comma in the name (no ticket)
  201. s := newTestServer(t, newTestConfig(t))
  202. response := request(t, s, "GET", "/mytopic,mytopic2/publish?m=hi", "", nil)
  203. require.Equal(t, 404, response.Code)
  204. }
  205. func TestServer_PublishNoCache(t *testing.T) {
  206. s := newTestServer(t, newTestConfig(t))
  207. response := request(t, s, "PUT", "/mytopic", "this message is not cached", map[string]string{
  208. "Cache": "no",
  209. })
  210. msg := toMessage(t, response.Body.String())
  211. require.NotEmpty(t, msg.ID)
  212. require.Equal(t, "this message is not cached", msg.Message)
  213. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  214. messages := toMessages(t, response.Body.String())
  215. require.Empty(t, messages)
  216. }
  217. func TestServer_PublishAt(t *testing.T) {
  218. c := newTestConfig(t)
  219. c.MinDelay = time.Second
  220. c.DelayedSenderInterval = 100 * time.Millisecond
  221. s := newTestServer(t, c)
  222. response := request(t, s, "PUT", "/mytopic", "a message", map[string]string{
  223. "In": "1s",
  224. })
  225. require.Equal(t, 200, response.Code)
  226. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  227. messages := toMessages(t, response.Body.String())
  228. require.Equal(t, 0, len(messages))
  229. time.Sleep(time.Second)
  230. require.Nil(t, s.sendDelayedMessages())
  231. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  232. messages = toMessages(t, response.Body.String())
  233. require.Equal(t, 1, len(messages))
  234. require.Equal(t, "a message", messages[0].Message)
  235. require.Equal(t, netip.Addr{}, messages[0].Sender) // Never return the sender!
  236. messages, err := s.messageCache.Messages("mytopic", sinceAllMessages, true)
  237. require.Nil(t, err)
  238. require.Equal(t, 1, len(messages))
  239. require.Equal(t, "a message", messages[0].Message)
  240. require.Equal(t, "9.9.9.9", messages[0].Sender.String()) // It's stored in the DB though!
  241. }
  242. func TestServer_PublishAtWithCacheError(t *testing.T) {
  243. s := newTestServer(t, newTestConfig(t))
  244. response := request(t, s, "PUT", "/mytopic", "a message", map[string]string{
  245. "Cache": "no",
  246. "In": "30 min",
  247. })
  248. require.Equal(t, 400, response.Code)
  249. require.Equal(t, errHTTPBadRequestDelayNoCache, toHTTPError(t, response.Body.String()))
  250. }
  251. func TestServer_PublishAtTooShortDelay(t *testing.T) {
  252. s := newTestServer(t, newTestConfig(t))
  253. response := request(t, s, "PUT", "/mytopic", "a message", map[string]string{
  254. "In": "1s",
  255. })
  256. require.Equal(t, 400, response.Code)
  257. }
  258. func TestServer_PublishAtTooLongDelay(t *testing.T) {
  259. s := newTestServer(t, newTestConfig(t))
  260. response := request(t, s, "PUT", "/mytopic", "a message", map[string]string{
  261. "In": "99999999h",
  262. })
  263. require.Equal(t, 400, response.Code)
  264. }
  265. func TestServer_PublishAtInvalidDelay(t *testing.T) {
  266. s := newTestServer(t, newTestConfig(t))
  267. response := request(t, s, "PUT", "/mytopic?delay=INVALID", "a message", nil)
  268. err := toHTTPError(t, response.Body.String())
  269. require.Equal(t, 400, response.Code)
  270. require.Equal(t, 40004, err.Code)
  271. }
  272. func TestServer_PublishAtTooLarge(t *testing.T) {
  273. s := newTestServer(t, newTestConfig(t))
  274. response := request(t, s, "PUT", "/mytopic?x-in=99999h", "a message", nil)
  275. err := toHTTPError(t, response.Body.String())
  276. require.Equal(t, 400, response.Code)
  277. require.Equal(t, 40006, err.Code)
  278. }
  279. func TestServer_PublishAtAndPrune(t *testing.T) {
  280. s := newTestServer(t, newTestConfig(t))
  281. response := request(t, s, "PUT", "/mytopic", "a message", map[string]string{
  282. "In": "1h",
  283. })
  284. require.Equal(t, 200, response.Code)
  285. s.execManager() // Fire pruning
  286. response = request(t, s, "GET", "/mytopic/json?poll=1&scheduled=1", "", nil)
  287. messages := toMessages(t, response.Body.String())
  288. require.Equal(t, 1, len(messages)) // Not affected by pruning
  289. require.Equal(t, "a message", messages[0].Message)
  290. }
  291. func TestServer_PublishAndMultiPoll(t *testing.T) {
  292. s := newTestServer(t, newTestConfig(t))
  293. response := request(t, s, "PUT", "/mytopic1", "message 1", nil)
  294. msg := toMessage(t, response.Body.String())
  295. require.NotEmpty(t, msg.ID)
  296. require.Equal(t, "mytopic1", msg.Topic)
  297. require.Equal(t, "message 1", msg.Message)
  298. response = request(t, s, "PUT", "/mytopic2", "message 2", nil)
  299. msg = toMessage(t, response.Body.String())
  300. require.NotEmpty(t, msg.ID)
  301. require.Equal(t, "mytopic2", msg.Topic)
  302. require.Equal(t, "message 2", msg.Message)
  303. response = request(t, s, "GET", "/mytopic1/json?poll=1", "", nil)
  304. messages := toMessages(t, response.Body.String())
  305. require.Equal(t, 1, len(messages))
  306. require.Equal(t, "mytopic1", messages[0].Topic)
  307. require.Equal(t, "message 1", messages[0].Message)
  308. response = request(t, s, "GET", "/mytopic1,mytopic2/json?poll=1", "", nil)
  309. messages = toMessages(t, response.Body.String())
  310. require.Equal(t, 2, len(messages))
  311. require.Equal(t, "mytopic1", messages[0].Topic)
  312. require.Equal(t, "message 1", messages[0].Message)
  313. require.Equal(t, "mytopic2", messages[1].Topic)
  314. require.Equal(t, "message 2", messages[1].Message)
  315. }
  316. func TestServer_PublishWithNopCache(t *testing.T) {
  317. c := newTestConfig(t)
  318. c.CacheDuration = 0
  319. s := newTestServer(t, c)
  320. subscribeRR := httptest.NewRecorder()
  321. subscribeCancel := subscribe(t, s, "/mytopic/json", subscribeRR)
  322. publishRR := request(t, s, "PUT", "/mytopic", "my first message", nil)
  323. require.Equal(t, 200, publishRR.Code)
  324. subscribeCancel()
  325. messages := toMessages(t, subscribeRR.Body.String())
  326. require.Equal(t, 2, len(messages))
  327. require.Equal(t, openEvent, messages[0].Event)
  328. require.Equal(t, messageEvent, messages[1].Event)
  329. require.Equal(t, "my first message", messages[1].Message)
  330. response := request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  331. messages = toMessages(t, response.Body.String())
  332. require.Empty(t, messages)
  333. }
  334. func TestServer_PublishAndPollSince(t *testing.T) {
  335. s := newTestServer(t, newTestConfig(t))
  336. request(t, s, "PUT", "/mytopic", "test 1", nil)
  337. time.Sleep(1100 * time.Millisecond)
  338. since := time.Now().Unix()
  339. request(t, s, "PUT", "/mytopic", "test 2", nil)
  340. response := request(t, s, "GET", fmt.Sprintf("/mytopic/json?poll=1&since=%d", since), "", nil)
  341. messages := toMessages(t, response.Body.String())
  342. require.Equal(t, 1, len(messages))
  343. require.Equal(t, "test 2", messages[0].Message)
  344. response = request(t, s, "GET", "/mytopic/json?poll=1&since=10s", "", nil)
  345. messages = toMessages(t, response.Body.String())
  346. require.Equal(t, 2, len(messages))
  347. require.Equal(t, "test 1", messages[0].Message)
  348. response = request(t, s, "GET", "/mytopic/json?poll=1&since=100ms", "", nil)
  349. messages = toMessages(t, response.Body.String())
  350. require.Equal(t, 1, len(messages))
  351. require.Equal(t, "test 2", messages[0].Message)
  352. response = request(t, s, "GET", "/mytopic/json?poll=1&since=INVALID", "", nil)
  353. require.Equal(t, 40008, toHTTPError(t, response.Body.String()).Code)
  354. }
  355. func newMessageWithTimestamp(topic, message string, timestamp int64) *message {
  356. m := newDefaultMessage(topic, message)
  357. m.Time = timestamp
  358. return m
  359. }
  360. func TestServer_PollSinceID_MultipleTopics(t *testing.T) {
  361. s := newTestServer(t, newTestConfig(t))
  362. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic1", "test 1", 1655740277)))
  363. markerMessage := newMessageWithTimestamp("mytopic2", "test 2", 1655740283)
  364. require.Nil(t, s.messageCache.AddMessage(markerMessage))
  365. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic1", "test 3", 1655740289)))
  366. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic2", "test 4", 1655740293)))
  367. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic1", "test 5", 1655740297)))
  368. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic2", "test 6", 1655740303)))
  369. response := request(t, s, "GET", fmt.Sprintf("/mytopic1,mytopic2/json?poll=1&since=%s", markerMessage.ID), "", nil)
  370. messages := toMessages(t, response.Body.String())
  371. require.Equal(t, 4, len(messages))
  372. require.Equal(t, "test 3", messages[0].Message)
  373. require.Equal(t, "mytopic1", messages[0].Topic)
  374. require.Equal(t, "test 4", messages[1].Message)
  375. require.Equal(t, "mytopic2", messages[1].Topic)
  376. require.Equal(t, "test 5", messages[2].Message)
  377. require.Equal(t, "mytopic1", messages[2].Topic)
  378. require.Equal(t, "test 6", messages[3].Message)
  379. require.Equal(t, "mytopic2", messages[3].Topic)
  380. }
  381. func TestServer_PollSinceID_MultipleTopics_IDDoesNotMatch(t *testing.T) {
  382. s := newTestServer(t, newTestConfig(t))
  383. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic1", "test 3", 1655740289)))
  384. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic2", "test 4", 1655740293)))
  385. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic1", "test 5", 1655740297)))
  386. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic2", "test 6", 1655740303)))
  387. response := request(t, s, "GET", "/mytopic1,mytopic2/json?poll=1&since=NoMatchForID", "", nil)
  388. messages := toMessages(t, response.Body.String())
  389. require.Equal(t, 4, len(messages))
  390. require.Equal(t, "test 3", messages[0].Message)
  391. require.Equal(t, "test 4", messages[1].Message)
  392. require.Equal(t, "test 5", messages[2].Message)
  393. require.Equal(t, "test 6", messages[3].Message)
  394. }
  395. func TestServer_PublishViaGET(t *testing.T) {
  396. s := newTestServer(t, newTestConfig(t))
  397. response := request(t, s, "GET", "/mytopic/trigger", "", nil)
  398. msg := toMessage(t, response.Body.String())
  399. require.NotEmpty(t, msg.ID)
  400. require.Equal(t, "triggered", msg.Message)
  401. 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)
  402. msg = toMessage(t, response.Body.String())
  403. require.NotEmpty(t, msg.ID)
  404. require.Equal(t, "This is a test", msg.Message)
  405. require.Equal(t, "This is a title", msg.Title)
  406. require.Equal(t, []string{"skull"}, msg.Tags)
  407. require.Equal(t, 5, msg.Priority)
  408. require.Greater(t, msg.Time, time.Now().Add(23*time.Hour).Unix())
  409. }
  410. func TestServer_PublishMessageInHeaderWithNewlines(t *testing.T) {
  411. s := newTestServer(t, newTestConfig(t))
  412. response := request(t, s, "PUT", "/mytopic", "", map[string]string{
  413. "Message": "Line 1\\nLine 2",
  414. })
  415. msg := toMessage(t, response.Body.String())
  416. require.NotEmpty(t, msg.ID)
  417. require.Equal(t, "Line 1\nLine 2", msg.Message) // \\n -> \n !
  418. }
  419. func TestServer_PublishInvalidTopic(t *testing.T) {
  420. s := newTestServer(t, newTestConfig(t))
  421. s.smtpSender = &testMailer{}
  422. response := request(t, s, "PUT", "/docs", "fail", nil)
  423. require.Equal(t, 40010, toHTTPError(t, response.Body.String()).Code)
  424. }
  425. func TestServer_PollWithQueryFilters(t *testing.T) {
  426. s := newTestServer(t, newTestConfig(t))
  427. response := request(t, s, "PUT", "/mytopic?priority=1&tags=tag1,tag2", "my first message", nil)
  428. msg := toMessage(t, response.Body.String())
  429. require.NotEmpty(t, msg.ID)
  430. response = request(t, s, "PUT", "/mytopic?title=a+title", "my second message", map[string]string{
  431. "Tags": "tag2,tag3",
  432. })
  433. msg = toMessage(t, response.Body.String())
  434. require.NotEmpty(t, msg.ID)
  435. queriesThatShouldReturnMessageOne := []string{
  436. "/mytopic/json?poll=1&priority=1",
  437. "/mytopic/json?poll=1&priority=min",
  438. "/mytopic/json?poll=1&priority=min,low",
  439. "/mytopic/json?poll=1&priority=1,2",
  440. "/mytopic/json?poll=1&p=2,min",
  441. "/mytopic/json?poll=1&tags=tag1",
  442. "/mytopic/json?poll=1&tags=tag1,tag2",
  443. "/mytopic/json?poll=1&message=my+first+message",
  444. }
  445. for _, query := range queriesThatShouldReturnMessageOne {
  446. response = request(t, s, "GET", query, "", nil)
  447. messages := toMessages(t, response.Body.String())
  448. require.Equal(t, 1, len(messages), "Query failed: "+query)
  449. require.Equal(t, "my first message", messages[0].Message, "Query failed: "+query)
  450. }
  451. queriesThatShouldReturnMessageTwo := []string{
  452. "/mytopic/json?poll=1&x-priority=3", // !
  453. "/mytopic/json?poll=1&priority=3",
  454. "/mytopic/json?poll=1&priority=default",
  455. "/mytopic/json?poll=1&p=3",
  456. "/mytopic/json?poll=1&x-tags=tag2,tag3",
  457. "/mytopic/json?poll=1&tags=tag2,tag3",
  458. "/mytopic/json?poll=1&tag=tag2,tag3",
  459. "/mytopic/json?poll=1&ta=tag2,tag3",
  460. "/mytopic/json?poll=1&x-title=a+title",
  461. "/mytopic/json?poll=1&title=a+title",
  462. "/mytopic/json?poll=1&t=a+title",
  463. "/mytopic/json?poll=1&x-message=my+second+message",
  464. "/mytopic/json?poll=1&message=my+second+message",
  465. "/mytopic/json?poll=1&m=my+second+message",
  466. "/mytopic/json?x-poll=1&m=my+second+message",
  467. "/mytopic/json?po=1&m=my+second+message",
  468. }
  469. for _, query := range queriesThatShouldReturnMessageTwo {
  470. response = request(t, s, "GET", query, "", nil)
  471. messages := toMessages(t, response.Body.String())
  472. require.Equal(t, 1, len(messages), "Query failed: "+query)
  473. require.Equal(t, "my second message", messages[0].Message, "Query failed: "+query)
  474. }
  475. queriesThatShouldReturnNoMessages := []string{
  476. "/mytopic/json?poll=1&priority=4",
  477. "/mytopic/json?poll=1&tags=tag1,tag2,tag3",
  478. "/mytopic/json?poll=1&title=another+title",
  479. "/mytopic/json?poll=1&message=my+third+message",
  480. "/mytopic/json?poll=1&message=my+third+message",
  481. }
  482. for _, query := range queriesThatShouldReturnNoMessages {
  483. response = request(t, s, "GET", query, "", nil)
  484. messages := toMessages(t, response.Body.String())
  485. require.Equal(t, 0, len(messages), "Query failed: "+query)
  486. }
  487. }
  488. func TestServer_SubscribeWithQueryFilters(t *testing.T) {
  489. c := newTestConfig(t)
  490. c.KeepaliveInterval = 800 * time.Millisecond
  491. s := newTestServer(t, c)
  492. subscribeResponse := httptest.NewRecorder()
  493. subscribeCancel := subscribe(t, s, "/mytopic/json?tags=zfs-issue", subscribeResponse)
  494. response := request(t, s, "PUT", "/mytopic", "my first message", nil)
  495. require.Equal(t, 200, response.Code)
  496. response = request(t, s, "PUT", "/mytopic", "ZFS scrub failed", map[string]string{
  497. "Tags": "zfs-issue,zfs-scrub",
  498. })
  499. require.Equal(t, 200, response.Code)
  500. time.Sleep(850 * time.Millisecond)
  501. subscribeCancel()
  502. messages := toMessages(t, subscribeResponse.Body.String())
  503. require.Equal(t, 3, len(messages))
  504. require.Equal(t, openEvent, messages[0].Event)
  505. require.Equal(t, messageEvent, messages[1].Event)
  506. require.Equal(t, "ZFS scrub failed", messages[1].Message)
  507. require.Equal(t, keepaliveEvent, messages[2].Event)
  508. }
  509. func TestServer_Auth_Success_Admin(t *testing.T) {
  510. c := newTestConfigWithAuthFile(t)
  511. s := newTestServer(t, c)
  512. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleAdmin, "unit-test"))
  513. response := request(t, s, "GET", "/mytopic/auth", "", map[string]string{
  514. "Authorization": util.BasicAuth("phil", "phil"),
  515. })
  516. require.Equal(t, 200, response.Code)
  517. require.Equal(t, `{"success":true}`+"\n", response.Body.String())
  518. }
  519. func TestServer_Auth_Success_User(t *testing.T) {
  520. c := newTestConfigWithAuthFile(t)
  521. c.AuthDefault = user.PermissionDenyAll
  522. s := newTestServer(t, c)
  523. require.Nil(t, s.userManager.AddUser("ben", "ben", user.RoleUser, "unit-test"))
  524. require.Nil(t, s.userManager.AllowAccess("ben", "mytopic", user.PermissionReadWrite))
  525. response := request(t, s, "GET", "/mytopic/auth", "", map[string]string{
  526. "Authorization": util.BasicAuth("ben", "ben"),
  527. })
  528. require.Equal(t, 200, response.Code)
  529. }
  530. func TestServer_Auth_Success_User_MultipleTopics(t *testing.T) {
  531. c := newTestConfigWithAuthFile(t)
  532. c.AuthDefault = user.PermissionDenyAll
  533. s := newTestServer(t, c)
  534. require.Nil(t, s.userManager.AddUser("ben", "ben", user.RoleUser, "unit-test"))
  535. require.Nil(t, s.userManager.AllowAccess("ben", "mytopic", user.PermissionReadWrite))
  536. require.Nil(t, s.userManager.AllowAccess("ben", "anothertopic", user.PermissionReadWrite))
  537. response := request(t, s, "GET", "/mytopic,anothertopic/auth", "", map[string]string{
  538. "Authorization": util.BasicAuth("ben", "ben"),
  539. })
  540. require.Equal(t, 200, response.Code)
  541. response = request(t, s, "GET", "/mytopic,anothertopic,NOT-THIS-ONE/auth", "", map[string]string{
  542. "Authorization": util.BasicAuth("ben", "ben"),
  543. })
  544. require.Equal(t, 403, response.Code)
  545. }
  546. func TestServer_Auth_Fail_InvalidPass(t *testing.T) {
  547. c := newTestConfig(t)
  548. c.AuthFile = filepath.Join(t.TempDir(), "user.db")
  549. c.AuthDefault = user.PermissionDenyAll
  550. s := newTestServer(t, c)
  551. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleAdmin, "unit-test"))
  552. response := request(t, s, "GET", "/mytopic/auth", "", map[string]string{
  553. "Authorization": util.BasicAuth("phil", "INVALID"),
  554. })
  555. require.Equal(t, 401, response.Code)
  556. }
  557. func TestServer_Auth_Fail_Unauthorized(t *testing.T) {
  558. c := newTestConfigWithAuthFile(t)
  559. c.AuthDefault = user.PermissionDenyAll
  560. s := newTestServer(t, c)
  561. require.Nil(t, s.userManager.AddUser("ben", "ben", user.RoleUser, "unit-test"))
  562. require.Nil(t, s.userManager.AllowAccess("ben", "sometopic", user.PermissionReadWrite)) // Not mytopic!
  563. response := request(t, s, "GET", "/mytopic/auth", "", map[string]string{
  564. "Authorization": util.BasicAuth("ben", "ben"),
  565. })
  566. require.Equal(t, 403, response.Code)
  567. }
  568. func TestServer_Auth_Fail_CannotPublish(t *testing.T) {
  569. c := newTestConfigWithAuthFile(t)
  570. c.AuthDefault = user.PermissionReadWrite // Open by default
  571. s := newTestServer(t, c)
  572. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleAdmin, "unit-test"))
  573. require.Nil(t, s.userManager.AllowAccess(user.Everyone, "private", user.PermissionDenyAll))
  574. require.Nil(t, s.userManager.AllowAccess(user.Everyone, "announcements", user.PermissionRead))
  575. response := request(t, s, "PUT", "/mytopic", "test", nil)
  576. require.Equal(t, 200, response.Code)
  577. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  578. require.Equal(t, 200, response.Code)
  579. response = request(t, s, "PUT", "/announcements", "test", nil)
  580. require.Equal(t, 403, response.Code) // Cannot write as anonymous
  581. response = request(t, s, "PUT", "/announcements", "test", map[string]string{
  582. "Authorization": util.BasicAuth("phil", "phil"),
  583. })
  584. require.Equal(t, 200, response.Code)
  585. response = request(t, s, "GET", "/announcements/json?poll=1", "", nil)
  586. require.Equal(t, 200, response.Code) // Anonymous read allowed
  587. response = request(t, s, "GET", "/private/json?poll=1", "", nil)
  588. require.Equal(t, 403, response.Code) // Anonymous read not allowed
  589. }
  590. func TestServer_Auth_ViaQuery(t *testing.T) {
  591. c := newTestConfigWithAuthFile(t)
  592. c.AuthDefault = user.PermissionDenyAll
  593. s := newTestServer(t, c)
  594. require.Nil(t, s.userManager.AddUser("ben", "some pass", user.RoleAdmin, "unit-test"))
  595. u := fmt.Sprintf("/mytopic/json?poll=1&auth=%s", base64.RawURLEncoding.EncodeToString([]byte(util.BasicAuth("ben", "some pass"))))
  596. response := request(t, s, "GET", u, "", nil)
  597. require.Equal(t, 200, response.Code)
  598. u = fmt.Sprintf("/mytopic/json?poll=1&auth=%s", base64.RawURLEncoding.EncodeToString([]byte(util.BasicAuth("ben", "WRONNNGGGG"))))
  599. response = request(t, s, "GET", u, "", nil)
  600. require.Equal(t, 401, response.Code)
  601. }
  602. func TestServer_StatsResetter(t *testing.T) {
  603. c := newTestConfigWithAuthFile(t)
  604. c.AuthDefault = user.PermissionDenyAll
  605. c.VisitorStatsResetTime = time.Now().Add(2 * time.Second)
  606. s := newTestServer(t, c)
  607. go s.runStatsResetter()
  608. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser, "unit-test"))
  609. require.Nil(t, s.userManager.AllowAccess("phil", "mytopic", user.PermissionReadWrite))
  610. for i := 0; i < 5; i++ {
  611. response := request(t, s, "PUT", "/mytopic", "test", map[string]string{
  612. "Authorization": util.BasicAuth("phil", "phil"),
  613. })
  614. require.Equal(t, 200, response.Code)
  615. }
  616. response := request(t, s, "GET", "/v1/account", "", map[string]string{
  617. "Authorization": util.BasicAuth("phil", "phil"),
  618. })
  619. require.Equal(t, 200, response.Code)
  620. // User stats show 10 messages
  621. response = request(t, s, "GET", "/v1/account", "", map[string]string{
  622. "Authorization": util.BasicAuth("phil", "phil"),
  623. })
  624. require.Equal(t, 200, response.Code)
  625. account, err := util.UnmarshalJSON[apiAccountResponse](io.NopCloser(response.Body))
  626. require.Nil(t, err)
  627. require.Equal(t, int64(5), account.Stats.Messages)
  628. // Wait for stats resetter to run
  629. time.Sleep(2200 * time.Millisecond)
  630. // User stats show 0 messages now!
  631. response = request(t, s, "GET", "/v1/account", "", nil)
  632. require.Equal(t, 200, response.Code)
  633. account, err = util.UnmarshalJSON[apiAccountResponse](io.NopCloser(response.Body))
  634. require.Nil(t, err)
  635. require.Equal(t, int64(0), account.Stats.Messages)
  636. }
  637. type testMailer struct {
  638. count int
  639. mu sync.Mutex
  640. }
  641. func (t *testMailer) Send(v *visitor, m *message, to string) error {
  642. t.mu.Lock()
  643. defer t.mu.Unlock()
  644. t.count++
  645. return nil
  646. }
  647. func (t *testMailer) Counts() (total int64, success int64, failure int64) {
  648. return 0, 0, 0
  649. }
  650. func (t *testMailer) Count() int {
  651. t.mu.Lock()
  652. defer t.mu.Unlock()
  653. return t.count
  654. }
  655. func TestServer_PublishTooRequests_Defaults(t *testing.T) {
  656. s := newTestServer(t, newTestConfig(t))
  657. for i := 0; i < 60; i++ {
  658. response := request(t, s, "PUT", "/mytopic", fmt.Sprintf("message %d", i), nil)
  659. require.Equal(t, 200, response.Code)
  660. }
  661. response := request(t, s, "PUT", "/mytopic", "message", nil)
  662. require.Equal(t, 429, response.Code)
  663. }
  664. func TestServer_PublishTooRequests_Defaults_ExemptHosts(t *testing.T) {
  665. c := newTestConfig(t)
  666. c.VisitorRequestExemptIPAddrs = []netip.Prefix{netip.MustParsePrefix("9.9.9.9/32")} // see request()
  667. s := newTestServer(t, c)
  668. for i := 0; i < 65; i++ { // > 60
  669. response := request(t, s, "PUT", "/mytopic", fmt.Sprintf("message %d", i), nil)
  670. require.Equal(t, 200, response.Code)
  671. }
  672. }
  673. func TestServer_PublishTooRequests_ShortReplenish(t *testing.T) {
  674. c := newTestConfig(t)
  675. c.VisitorRequestLimitBurst = 60
  676. c.VisitorRequestLimitReplenish = 500 * time.Millisecond
  677. s := newTestServer(t, c)
  678. for i := 0; i < 60; i++ {
  679. response := request(t, s, "PUT", "/mytopic", fmt.Sprintf("message %d", i), nil)
  680. require.Equal(t, 200, response.Code)
  681. }
  682. response := request(t, s, "PUT", "/mytopic", "message", nil)
  683. require.Equal(t, 429, response.Code)
  684. time.Sleep(520 * time.Millisecond)
  685. response = request(t, s, "PUT", "/mytopic", "message", nil)
  686. require.Equal(t, 200, response.Code)
  687. }
  688. func TestServer_PublishTooManyEmails_Defaults(t *testing.T) {
  689. s := newTestServer(t, newTestConfig(t))
  690. s.smtpSender = &testMailer{}
  691. for i := 0; i < 16; i++ {
  692. response := request(t, s, "PUT", "/mytopic", fmt.Sprintf("message %d", i), map[string]string{
  693. "E-Mail": "test@example.com",
  694. })
  695. require.Equal(t, 200, response.Code)
  696. }
  697. response := request(t, s, "PUT", "/mytopic", "one too many", map[string]string{
  698. "E-Mail": "test@example.com",
  699. })
  700. require.Equal(t, 429, response.Code)
  701. }
  702. func TestServer_PublishTooManyEmails_Replenish(t *testing.T) {
  703. c := newTestConfig(t)
  704. c.VisitorEmailLimitReplenish = 500 * time.Millisecond
  705. s := newTestServer(t, c)
  706. s.smtpSender = &testMailer{}
  707. for i := 0; i < 16; i++ {
  708. response := request(t, s, "PUT", "/mytopic", fmt.Sprintf("message %d", i), map[string]string{
  709. "E-Mail": "test@example.com",
  710. })
  711. require.Equal(t, 200, response.Code)
  712. }
  713. response := request(t, s, "PUT", "/mytopic", "one too many", map[string]string{
  714. "E-Mail": "test@example.com",
  715. })
  716. require.Equal(t, 429, response.Code)
  717. time.Sleep(510 * time.Millisecond)
  718. response = request(t, s, "PUT", "/mytopic", "this should be okay again too many", map[string]string{
  719. "E-Mail": "test@example.com",
  720. })
  721. require.Equal(t, 200, response.Code)
  722. response = request(t, s, "PUT", "/mytopic", "and bad again", map[string]string{
  723. "E-Mail": "test@example.com",
  724. })
  725. require.Equal(t, 429, response.Code)
  726. }
  727. func TestServer_PublishDelayedEmail_Fail(t *testing.T) {
  728. s := newTestServer(t, newTestConfig(t))
  729. s.smtpSender = &testMailer{}
  730. response := request(t, s, "PUT", "/mytopic", "fail", map[string]string{
  731. "E-Mail": "test@example.com",
  732. "Delay": "20 min",
  733. })
  734. require.Equal(t, 400, response.Code)
  735. }
  736. func TestServer_PublishEmailNoMailer_Fail(t *testing.T) {
  737. s := newTestServer(t, newTestConfig(t))
  738. response := request(t, s, "PUT", "/mytopic", "fail", map[string]string{
  739. "E-Mail": "test@example.com",
  740. })
  741. require.Equal(t, 400, response.Code)
  742. }
  743. func TestServer_UnifiedPushDiscovery(t *testing.T) {
  744. s := newTestServer(t, newTestConfig(t))
  745. response := request(t, s, "GET", "/mytopic?up=1", "", nil)
  746. require.Equal(t, 200, response.Code)
  747. require.Equal(t, `{"unifiedpush":{"version":1}}`+"\n", response.Body.String())
  748. }
  749. func TestServer_PublishUnifiedPushBinary_AndPoll(t *testing.T) {
  750. b := make([]byte, 12) // Max length
  751. _, err := rand.Read(b)
  752. require.Nil(t, err)
  753. s := newTestServer(t, newTestConfig(t))
  754. response := request(t, s, "PUT", "/mytopic?up=1", string(b), nil)
  755. require.Equal(t, 200, response.Code)
  756. m := toMessage(t, response.Body.String())
  757. require.Equal(t, "base64", m.Encoding)
  758. b2, err := base64.StdEncoding.DecodeString(m.Message)
  759. require.Nil(t, err)
  760. require.Equal(t, b, b2)
  761. response = request(t, s, "GET", "/mytopic/json?poll=1", string(b), nil)
  762. require.Equal(t, 200, response.Code)
  763. m = toMessage(t, response.Body.String())
  764. require.Equal(t, "base64", m.Encoding)
  765. b2, err = base64.StdEncoding.DecodeString(m.Message)
  766. require.Nil(t, err)
  767. require.Equal(t, b, b2)
  768. }
  769. func TestServer_PublishUnifiedPushBinary_Truncated(t *testing.T) {
  770. b := make([]byte, 5000) // Longer than max length
  771. _, err := rand.Read(b)
  772. require.Nil(t, err)
  773. s := newTestServer(t, newTestConfig(t))
  774. response := request(t, s, "PUT", "/mytopic?up=1", string(b), nil)
  775. require.Equal(t, 200, response.Code)
  776. m := toMessage(t, response.Body.String())
  777. require.Equal(t, "base64", m.Encoding)
  778. b2, err := base64.StdEncoding.DecodeString(m.Message)
  779. require.Nil(t, err)
  780. require.Equal(t, 4096, len(b2))
  781. require.Equal(t, b[:4096], b2)
  782. }
  783. func TestServer_PublishUnifiedPushText(t *testing.T) {
  784. s := newTestServer(t, newTestConfig(t))
  785. response := request(t, s, "PUT", "/mytopic?up=1", "this is a unifiedpush text message", nil)
  786. require.Equal(t, 200, response.Code)
  787. m := toMessage(t, response.Body.String())
  788. require.Equal(t, "", m.Encoding)
  789. require.Equal(t, "this is a unifiedpush text message", m.Message)
  790. }
  791. func TestServer_MatrixGateway_Discovery_Success(t *testing.T) {
  792. s := newTestServer(t, newTestConfig(t))
  793. response := request(t, s, "GET", "/_matrix/push/v1/notify", "", nil)
  794. require.Equal(t, 200, response.Code)
  795. require.Equal(t, `{"unifiedpush":{"gateway":"matrix"}}`+"\n", response.Body.String())
  796. }
  797. func TestServer_MatrixGateway_Discovery_Failure_Unconfigured(t *testing.T) {
  798. c := newTestConfig(t)
  799. c.BaseURL = ""
  800. s := newTestServer(t, c)
  801. response := request(t, s, "GET", "/_matrix/push/v1/notify", "", nil)
  802. require.Equal(t, 500, response.Code)
  803. err := toHTTPError(t, response.Body.String())
  804. require.Equal(t, 50003, err.Code)
  805. }
  806. func TestServer_MatrixGateway_Push_Success(t *testing.T) {
  807. s := newTestServer(t, newTestConfig(t))
  808. notification := `{"notification":{"devices":[{"pushkey":"http://127.0.0.1:12345/mytopic?up=1"}]}}`
  809. response := request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  810. require.Equal(t, 200, response.Code)
  811. require.Equal(t, `{"rejected":[]}`+"\n", response.Body.String())
  812. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  813. require.Equal(t, 200, response.Code)
  814. m := toMessage(t, response.Body.String())
  815. require.Equal(t, notification, m.Message)
  816. }
  817. func TestServer_MatrixGateway_Push_Failure_InvalidPushkey(t *testing.T) {
  818. s := newTestServer(t, newTestConfig(t))
  819. notification := `{"notification":{"devices":[{"pushkey":"http://wrong-base-url.com/mytopic?up=1"}]}}`
  820. response := request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  821. require.Equal(t, 200, response.Code)
  822. require.Equal(t, `{"rejected":["http://wrong-base-url.com/mytopic?up=1"]}`+"\n", response.Body.String())
  823. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  824. require.Equal(t, 200, response.Code)
  825. require.Equal(t, "", response.Body.String()) // Empty!
  826. }
  827. func TestServer_MatrixGateway_Push_Failure_EverythingIsWrong(t *testing.T) {
  828. s := newTestServer(t, newTestConfig(t))
  829. notification := `{"message":"this is not really a Matrix message"}`
  830. response := request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  831. require.Equal(t, 400, response.Code)
  832. err := toHTTPError(t, response.Body.String())
  833. require.Equal(t, 40019, err.Code)
  834. require.Equal(t, 400, err.HTTPCode)
  835. }
  836. func TestServer_MatrixGateway_Push_Failure_Unconfigured(t *testing.T) {
  837. c := newTestConfig(t)
  838. c.BaseURL = ""
  839. s := newTestServer(t, c)
  840. notification := `{"notification":{"devices":[{"pushkey":"http://127.0.0.1:12345/mytopic?up=1"}]}}`
  841. response := request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  842. require.Equal(t, 500, response.Code)
  843. err := toHTTPError(t, response.Body.String())
  844. require.Equal(t, 50003, err.Code)
  845. require.Equal(t, 500, err.HTTPCode)
  846. }
  847. func TestServer_PublishActions_AndPoll(t *testing.T) {
  848. s := newTestServer(t, newTestConfig(t))
  849. response := request(t, s, "PUT", "/mytopic", "my message", map[string]string{
  850. "Actions": "view, Open portal, https://home.nest.com/; http, Turn down, https://api.nest.com/device/XZ1D2, body=target_temp_f=65",
  851. })
  852. require.Equal(t, 200, response.Code)
  853. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  854. require.Equal(t, 200, response.Code)
  855. m := toMessage(t, response.Body.String())
  856. require.Equal(t, 2, len(m.Actions))
  857. require.Equal(t, "view", m.Actions[0].Action)
  858. require.Equal(t, "Open portal", m.Actions[0].Label)
  859. require.Equal(t, "https://home.nest.com/", m.Actions[0].URL)
  860. require.Equal(t, "http", m.Actions[1].Action)
  861. require.Equal(t, "Turn down", m.Actions[1].Label)
  862. require.Equal(t, "https://api.nest.com/device/XZ1D2", m.Actions[1].URL)
  863. require.Equal(t, "target_temp_f=65", m.Actions[1].Body)
  864. }
  865. func TestServer_PublishAsJSON(t *testing.T) {
  866. s := newTestServer(t, newTestConfig(t))
  867. body := `{"topic":"mytopic","message":"A message","title":"a title\nwith lines","tags":["tag1","tag 2"],` +
  868. `"not-a-thing":"ok", "attach":"http://google.com","filename":"google.pdf", "click":"http://ntfy.sh","priority":4,` +
  869. `"icon":"https://ntfy.sh/static/img/ntfy.png", "delay":"30min"}`
  870. response := request(t, s, "PUT", "/", body, nil)
  871. require.Equal(t, 200, response.Code)
  872. m := toMessage(t, response.Body.String())
  873. require.Equal(t, "mytopic", m.Topic)
  874. require.Equal(t, "A message", m.Message)
  875. require.Equal(t, "a title\nwith lines", m.Title)
  876. require.Equal(t, []string{"tag1", "tag 2"}, m.Tags)
  877. require.Equal(t, "http://google.com", m.Attachment.URL)
  878. require.Equal(t, "google.pdf", m.Attachment.Name)
  879. require.Equal(t, "http://ntfy.sh", m.Click)
  880. require.Equal(t, "https://ntfy.sh/static/img/ntfy.png", m.Icon)
  881. require.Equal(t, 4, m.Priority)
  882. require.True(t, m.Time > time.Now().Unix()+29*60)
  883. require.True(t, m.Time < time.Now().Unix()+31*60)
  884. }
  885. func TestServer_PublishAsJSON_WithEmail(t *testing.T) {
  886. mailer := &testMailer{}
  887. s := newTestServer(t, newTestConfig(t))
  888. s.smtpSender = mailer
  889. body := `{"topic":"mytopic","message":"A message","email":"phil@example.com"}`
  890. response := request(t, s, "PUT", "/", body, nil)
  891. require.Equal(t, 200, response.Code)
  892. time.Sleep(100 * time.Millisecond) // E-Mail publishing happens in a Go routine
  893. m := toMessage(t, response.Body.String())
  894. require.Equal(t, "mytopic", m.Topic)
  895. require.Equal(t, "A message", m.Message)
  896. require.Equal(t, 1, mailer.Count())
  897. }
  898. func TestServer_PublishAsJSON_WithActions(t *testing.T) {
  899. s := newTestServer(t, newTestConfig(t))
  900. body := `{
  901. "topic":"mytopic",
  902. "message":"A message",
  903. "actions": [
  904. {
  905. "action": "view",
  906. "label": "Open portal",
  907. "url": "https://home.nest.com/"
  908. },
  909. {
  910. "action": "http",
  911. "label": "Turn down",
  912. "url": "https://api.nest.com/device/XZ1D2",
  913. "body": "target_temp_f=65"
  914. }
  915. ]
  916. }`
  917. response := request(t, s, "POST", "/", body, nil)
  918. require.Equal(t, 200, response.Code)
  919. m := toMessage(t, response.Body.String())
  920. require.Equal(t, "mytopic", m.Topic)
  921. require.Equal(t, "A message", m.Message)
  922. require.Equal(t, 2, len(m.Actions))
  923. require.Equal(t, "view", m.Actions[0].Action)
  924. require.Equal(t, "Open portal", m.Actions[0].Label)
  925. require.Equal(t, "https://home.nest.com/", m.Actions[0].URL)
  926. require.Equal(t, "http", m.Actions[1].Action)
  927. require.Equal(t, "Turn down", m.Actions[1].Label)
  928. require.Equal(t, "https://api.nest.com/device/XZ1D2", m.Actions[1].URL)
  929. require.Equal(t, "target_temp_f=65", m.Actions[1].Body)
  930. }
  931. func TestServer_PublishAsJSON_Invalid(t *testing.T) {
  932. s := newTestServer(t, newTestConfig(t))
  933. body := `{"topic":"mytopic",INVALID`
  934. response := request(t, s, "PUT", "/", body, nil)
  935. require.Equal(t, 400, response.Code)
  936. }
  937. func TestServer_PublishWithTierBasedMessageLimitAndExpiry(t *testing.T) {
  938. c := newTestConfigWithAuthFile(t)
  939. s := newTestServer(t, c)
  940. // Create tier with certain limits
  941. require.Nil(t, s.userManager.CreateTier(&user.Tier{
  942. Code: "test",
  943. MessagesLimit: 5,
  944. MessagesExpiryDuration: -5 * time.Second, // Second, what a hack!
  945. }))
  946. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser, "unit-test"))
  947. require.Nil(t, s.userManager.ChangeTier("phil", "test"))
  948. // Publish to reach message limit
  949. for i := 0; i < 5; i++ {
  950. response := request(t, s, "PUT", "/mytopic", fmt.Sprintf("this is message %d", i+1), map[string]string{
  951. "Authorization": util.BasicAuth("phil", "phil"),
  952. })
  953. require.Equal(t, 200, response.Code)
  954. msg := toMessage(t, response.Body.String())
  955. require.True(t, msg.Expires < time.Now().Unix()+5)
  956. }
  957. response := request(t, s, "PUT", "/mytopic", "this is too much", map[string]string{
  958. "Authorization": util.BasicAuth("phil", "phil"),
  959. })
  960. require.Equal(t, 429, response.Code)
  961. // Run pruning and see if they are gone
  962. s.execManager()
  963. response = request(t, s, "GET", "/mytopic/json?poll=1", "", map[string]string{
  964. "Authorization": util.BasicAuth("phil", "phil"),
  965. })
  966. require.Equal(t, 200, response.Code)
  967. require.Empty(t, response.Body)
  968. }
  969. func TestServer_PublishAttachment(t *testing.T) {
  970. content := util.RandomString(5000) // > 4096
  971. s := newTestServer(t, newTestConfig(t))
  972. response := request(t, s, "PUT", "/mytopic", content, nil)
  973. msg := toMessage(t, response.Body.String())
  974. require.Equal(t, "attachment.txt", msg.Attachment.Name)
  975. require.Equal(t, "text/plain; charset=utf-8", msg.Attachment.Type)
  976. require.Equal(t, int64(5000), msg.Attachment.Size)
  977. require.GreaterOrEqual(t, msg.Attachment.Expires, time.Now().Add(179*time.Minute).Unix()) // Almost 3 hours
  978. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  979. require.Equal(t, netip.Addr{}, msg.Sender) // Should never be returned
  980. require.FileExists(t, filepath.Join(s.config.AttachmentCacheDir, msg.ID))
  981. // GET
  982. path := strings.TrimPrefix(msg.Attachment.URL, "http://127.0.0.1:12345")
  983. response = request(t, s, "GET", path, "", nil)
  984. require.Equal(t, 200, response.Code)
  985. require.Equal(t, "5000", response.Header().Get("Content-Length"))
  986. require.Equal(t, content, response.Body.String())
  987. // HEAD
  988. response = request(t, s, "HEAD", path, "", nil)
  989. require.Equal(t, 200, response.Code)
  990. require.Equal(t, "5000", response.Header().Get("Content-Length"))
  991. require.Equal(t, "", response.Body.String())
  992. // Slightly unrelated cross-test: make sure we add an owner for internal attachments
  993. size, err := s.messageCache.AttachmentBytesUsedBySender("9.9.9.9") // See request()
  994. require.Nil(t, err)
  995. require.Equal(t, int64(5000), size)
  996. }
  997. func TestServer_PublishAttachmentShortWithFilename(t *testing.T) {
  998. c := newTestConfig(t)
  999. c.BehindProxy = true
  1000. s := newTestServer(t, c)
  1001. content := "this is an ATTACHMENT"
  1002. response := request(t, s, "PUT", "/mytopic?f=myfile.txt", content, map[string]string{
  1003. "X-Forwarded-For": "1.2.3.4",
  1004. })
  1005. msg := toMessage(t, response.Body.String())
  1006. require.Equal(t, "myfile.txt", msg.Attachment.Name)
  1007. require.Equal(t, "text/plain; charset=utf-8", msg.Attachment.Type)
  1008. require.Equal(t, int64(21), msg.Attachment.Size)
  1009. require.GreaterOrEqual(t, msg.Attachment.Expires, time.Now().Add(3*time.Hour).Unix())
  1010. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1011. require.Equal(t, netip.Addr{}, msg.Sender) // Should never be returned
  1012. require.FileExists(t, filepath.Join(s.config.AttachmentCacheDir, msg.ID))
  1013. path := strings.TrimPrefix(msg.Attachment.URL, "http://127.0.0.1:12345")
  1014. response = request(t, s, "GET", path, "", nil)
  1015. require.Equal(t, 200, response.Code)
  1016. require.Equal(t, "21", response.Header().Get("Content-Length"))
  1017. require.Equal(t, content, response.Body.String())
  1018. // Slightly unrelated cross-test: make sure we add an owner for internal attachments
  1019. size, err := s.messageCache.AttachmentBytesUsedBySender("1.2.3.4")
  1020. require.Nil(t, err)
  1021. require.Equal(t, int64(21), size)
  1022. }
  1023. func TestServer_PublishAttachmentExternalWithoutFilename(t *testing.T) {
  1024. s := newTestServer(t, newTestConfig(t))
  1025. response := request(t, s, "PUT", "/mytopic", "", map[string]string{
  1026. "Attach": "https://upload.wikimedia.org/wikipedia/commons/f/fd/Pink_flower.jpg",
  1027. })
  1028. msg := toMessage(t, response.Body.String())
  1029. require.Equal(t, "You received a file: Pink_flower.jpg", msg.Message)
  1030. require.Equal(t, "Pink_flower.jpg", msg.Attachment.Name)
  1031. require.Equal(t, "https://upload.wikimedia.org/wikipedia/commons/f/fd/Pink_flower.jpg", msg.Attachment.URL)
  1032. require.Equal(t, "", msg.Attachment.Type)
  1033. require.Equal(t, int64(0), msg.Attachment.Size)
  1034. require.Equal(t, int64(0), msg.Attachment.Expires)
  1035. require.Equal(t, netip.Addr{}, msg.Sender)
  1036. // Slightly unrelated cross-test: make sure we don't add an owner for external attachments
  1037. size, err := s.messageCache.AttachmentBytesUsedBySender("127.0.0.1")
  1038. require.Nil(t, err)
  1039. require.Equal(t, int64(0), size)
  1040. }
  1041. func TestServer_PublishAttachmentExternalWithFilename(t *testing.T) {
  1042. s := newTestServer(t, newTestConfig(t))
  1043. response := request(t, s, "PUT", "/mytopic", "This is a custom message", map[string]string{
  1044. "X-Attach": "https://upload.wikimedia.org/wikipedia/commons/f/fd/Pink_flower.jpg",
  1045. "File": "some file.jpg",
  1046. })
  1047. msg := toMessage(t, response.Body.String())
  1048. require.Equal(t, "This is a custom message", msg.Message)
  1049. require.Equal(t, "some file.jpg", msg.Attachment.Name)
  1050. require.Equal(t, "https://upload.wikimedia.org/wikipedia/commons/f/fd/Pink_flower.jpg", msg.Attachment.URL)
  1051. require.Equal(t, "", msg.Attachment.Type)
  1052. require.Equal(t, int64(0), msg.Attachment.Size)
  1053. require.Equal(t, int64(0), msg.Attachment.Expires)
  1054. require.Equal(t, netip.Addr{}, msg.Sender)
  1055. }
  1056. func TestServer_PublishAttachmentBadURL(t *testing.T) {
  1057. s := newTestServer(t, newTestConfig(t))
  1058. response := request(t, s, "PUT", "/mytopic?a=not+a+URL", "", nil)
  1059. err := toHTTPError(t, response.Body.String())
  1060. require.Equal(t, 400, response.Code)
  1061. require.Equal(t, 400, err.HTTPCode)
  1062. require.Equal(t, 40013, err.Code)
  1063. }
  1064. func TestServer_PublishAttachmentTooLargeContentLength(t *testing.T) {
  1065. content := util.RandomString(5000) // > 4096
  1066. s := newTestServer(t, newTestConfig(t))
  1067. response := request(t, s, "PUT", "/mytopic", content, map[string]string{
  1068. "Content-Length": "20000000",
  1069. })
  1070. err := toHTTPError(t, response.Body.String())
  1071. require.Equal(t, 413, response.Code)
  1072. require.Equal(t, 413, err.HTTPCode)
  1073. require.Equal(t, 41301, err.Code)
  1074. }
  1075. func TestServer_PublishAttachmentTooLargeBodyAttachmentFileSizeLimit(t *testing.T) {
  1076. content := util.RandomString(5001) // > 5000, see below
  1077. c := newTestConfig(t)
  1078. c.AttachmentFileSizeLimit = 5000
  1079. s := newTestServer(t, c)
  1080. response := request(t, s, "PUT", "/mytopic", content, nil)
  1081. err := toHTTPError(t, response.Body.String())
  1082. require.Equal(t, 413, response.Code)
  1083. require.Equal(t, 413, err.HTTPCode)
  1084. require.Equal(t, 41301, err.Code)
  1085. }
  1086. func TestServer_PublishAttachmentExpiryBeforeDelivery(t *testing.T) {
  1087. c := newTestConfig(t)
  1088. c.AttachmentExpiryDuration = 10 * time.Minute
  1089. s := newTestServer(t, c)
  1090. response := request(t, s, "PUT", "/mytopic", util.RandomString(5000), map[string]string{
  1091. "Delay": "11 min", // > AttachmentExpiryDuration
  1092. })
  1093. err := toHTTPError(t, response.Body.String())
  1094. require.Equal(t, 400, response.Code)
  1095. require.Equal(t, 400, err.HTTPCode)
  1096. require.Equal(t, 40015, err.Code)
  1097. }
  1098. func TestServer_PublishAttachmentTooLargeBodyVisitorAttachmentTotalSizeLimit(t *testing.T) {
  1099. c := newTestConfig(t)
  1100. c.VisitorAttachmentTotalSizeLimit = 10000
  1101. s := newTestServer(t, c)
  1102. response := request(t, s, "PUT", "/mytopic", util.RandomString(5000), nil)
  1103. msg := toMessage(t, response.Body.String())
  1104. require.Equal(t, 200, response.Code)
  1105. require.Equal(t, "You received a file: attachment.txt", msg.Message)
  1106. require.Equal(t, int64(5000), msg.Attachment.Size)
  1107. content := util.RandomString(5001) // 5000+5001 > , see below
  1108. response = request(t, s, "PUT", "/mytopic", content, nil)
  1109. err := toHTTPError(t, response.Body.String())
  1110. require.Equal(t, 413, response.Code)
  1111. require.Equal(t, 413, err.HTTPCode)
  1112. require.Equal(t, 41301, err.Code)
  1113. }
  1114. func TestServer_PublishAttachmentAndExpire(t *testing.T) {
  1115. content := util.RandomString(5000) // > 4096
  1116. c := newTestConfig(t)
  1117. c.AttachmentExpiryDuration = time.Millisecond // Hack
  1118. s := newTestServer(t, c)
  1119. // Publish and make sure we can retrieve it
  1120. response := request(t, s, "PUT", "/mytopic", content, nil)
  1121. msg := toMessage(t, response.Body.String())
  1122. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1123. file := filepath.Join(s.config.AttachmentCacheDir, msg.ID)
  1124. require.FileExists(t, file)
  1125. path := strings.TrimPrefix(msg.Attachment.URL, "http://127.0.0.1:12345")
  1126. response = request(t, s, "GET", path, "", nil)
  1127. require.Equal(t, 200, response.Code)
  1128. require.Equal(t, content, response.Body.String())
  1129. // Prune and makes sure it's gone
  1130. time.Sleep(time.Second) // Sigh ...
  1131. s.execManager()
  1132. require.NoFileExists(t, file)
  1133. response = request(t, s, "GET", path, "", nil)
  1134. require.Equal(t, 404, response.Code)
  1135. }
  1136. func TestServer_PublishAttachmentWithTierBasedExpiry(t *testing.T) {
  1137. content := util.RandomString(5000) // > 4096
  1138. c := newTestConfigWithAuthFile(t)
  1139. c.AttachmentExpiryDuration = time.Millisecond // Hack
  1140. s := newTestServer(t, c)
  1141. // Create tier with certain limits
  1142. sevenDays := time.Duration(604800) * time.Second
  1143. require.Nil(t, s.userManager.CreateTier(&user.Tier{
  1144. Code: "test",
  1145. MessagesLimit: 10,
  1146. MessagesExpiryDuration: sevenDays,
  1147. AttachmentFileSizeLimit: 50_000,
  1148. AttachmentTotalSizeLimit: 200_000,
  1149. AttachmentExpiryDuration: sevenDays, // 7 days
  1150. }))
  1151. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser, "unit-test"))
  1152. require.Nil(t, s.userManager.ChangeTier("phil", "test"))
  1153. // Publish and make sure we can retrieve it
  1154. response := request(t, s, "PUT", "/mytopic", content, map[string]string{
  1155. "Authorization": util.BasicAuth("phil", "phil"),
  1156. })
  1157. msg := toMessage(t, response.Body.String())
  1158. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1159. require.True(t, msg.Attachment.Expires > time.Now().Add(sevenDays-30*time.Second).Unix())
  1160. require.True(t, msg.Expires > time.Now().Add(sevenDays-30*time.Second).Unix())
  1161. file := filepath.Join(s.config.AttachmentCacheDir, msg.ID)
  1162. require.FileExists(t, file)
  1163. path := strings.TrimPrefix(msg.Attachment.URL, "http://127.0.0.1:12345")
  1164. response = request(t, s, "GET", path, "", nil)
  1165. require.Equal(t, 200, response.Code)
  1166. require.Equal(t, content, response.Body.String())
  1167. // Prune and makes sure it's still there
  1168. time.Sleep(time.Second) // Sigh ...
  1169. s.execManager()
  1170. require.FileExists(t, file)
  1171. response = request(t, s, "GET", path, "", nil)
  1172. require.Equal(t, 200, response.Code)
  1173. }
  1174. func TestServer_PublishAttachmentWithTierBasedLimits(t *testing.T) {
  1175. smallFile := util.RandomString(20_000)
  1176. largeFile := util.RandomString(50_000)
  1177. c := newTestConfigWithAuthFile(t)
  1178. c.AttachmentFileSizeLimit = 20_000
  1179. c.VisitorAttachmentTotalSizeLimit = 40_000
  1180. s := newTestServer(t, c)
  1181. // Create tier with certain limits
  1182. require.Nil(t, s.userManager.CreateTier(&user.Tier{
  1183. Code: "test",
  1184. MessagesLimit: 100,
  1185. AttachmentFileSizeLimit: 50_000,
  1186. AttachmentTotalSizeLimit: 200_000,
  1187. AttachmentExpiryDuration: 30 * time.Second,
  1188. }))
  1189. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser, "unit-test"))
  1190. require.Nil(t, s.userManager.ChangeTier("phil", "test"))
  1191. // Publish small file as anonymous
  1192. response := request(t, s, "PUT", "/mytopic", smallFile, nil)
  1193. msg := toMessage(t, response.Body.String())
  1194. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1195. require.FileExists(t, filepath.Join(s.config.AttachmentCacheDir, msg.ID))
  1196. // Publish large file as anonymous
  1197. response = request(t, s, "PUT", "/mytopic", largeFile, nil)
  1198. require.Equal(t, 413, response.Code)
  1199. require.Equal(t, 41301, toHTTPError(t, response.Body.String()).Code)
  1200. // Publish too large file as phil
  1201. response = request(t, s, "PUT", "/mytopic", largeFile+" a few more bytes", map[string]string{
  1202. "Authorization": util.BasicAuth("phil", "phil"),
  1203. })
  1204. require.Equal(t, 413, response.Code)
  1205. require.Equal(t, 41301, toHTTPError(t, response.Body.String()).Code)
  1206. // Publish large file as phil (4x)
  1207. for i := 0; i < 4; i++ {
  1208. response = request(t, s, "PUT", "/mytopic", largeFile, map[string]string{
  1209. "Authorization": util.BasicAuth("phil", "phil"),
  1210. })
  1211. require.Equal(t, 200, response.Code)
  1212. msg = toMessage(t, response.Body.String())
  1213. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1214. require.FileExists(t, filepath.Join(s.config.AttachmentCacheDir, msg.ID))
  1215. }
  1216. response = request(t, s, "PUT", "/mytopic", largeFile, map[string]string{
  1217. "Authorization": util.BasicAuth("phil", "phil"),
  1218. })
  1219. require.Equal(t, 413, response.Code)
  1220. require.Equal(t, 41301, toHTTPError(t, response.Body.String()).Code)
  1221. }
  1222. func TestServer_PublishAttachmentBandwidthLimit(t *testing.T) {
  1223. content := util.RandomString(5000) // > 4096
  1224. c := newTestConfig(t)
  1225. c.VisitorAttachmentDailyBandwidthLimit = 5*5000 + 123 // A little more than 1 upload and 3 downloads
  1226. s := newTestServer(t, c)
  1227. // Publish attachment
  1228. response := request(t, s, "PUT", "/mytopic", content, nil)
  1229. msg := toMessage(t, response.Body.String())
  1230. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1231. // Value it 4 times successfully
  1232. path := strings.TrimPrefix(msg.Attachment.URL, "http://127.0.0.1:12345")
  1233. for i := 1; i <= 4; i++ { // 4 successful downloads
  1234. response = request(t, s, "GET", path, "", nil)
  1235. require.Equal(t, 200, response.Code)
  1236. require.Equal(t, content, response.Body.String())
  1237. }
  1238. // And then fail with a 429
  1239. response = request(t, s, "GET", path, "", nil)
  1240. err := toHTTPError(t, response.Body.String())
  1241. require.Equal(t, 429, response.Code)
  1242. require.Equal(t, 42905, err.Code)
  1243. }
  1244. func TestServer_PublishAttachmentBandwidthLimitUploadOnly(t *testing.T) {
  1245. content := util.RandomString(5000) // > 4096
  1246. c := newTestConfig(t)
  1247. c.VisitorAttachmentDailyBandwidthLimit = 5*5000 + 500 // 5 successful uploads
  1248. s := newTestServer(t, c)
  1249. // 5 successful uploads
  1250. for i := 1; i <= 5; i++ {
  1251. response := request(t, s, "PUT", "/mytopic", content, nil)
  1252. msg := toMessage(t, response.Body.String())
  1253. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1254. }
  1255. // And a failed one
  1256. response := request(t, s, "PUT", "/mytopic", content, nil)
  1257. err := toHTTPError(t, response.Body.String())
  1258. require.Equal(t, 413, response.Code)
  1259. require.Equal(t, 41301, err.Code)
  1260. }
  1261. func TestServer_PublishAttachmentAccountStats(t *testing.T) {
  1262. content := util.RandomString(4999) // > 4096
  1263. c := newTestConfig(t)
  1264. c.AttachmentFileSizeLimit = 5000
  1265. c.VisitorAttachmentTotalSizeLimit = 6000
  1266. s := newTestServer(t, c)
  1267. // Upload one attachment
  1268. response := request(t, s, "PUT", "/mytopic", content, nil)
  1269. msg := toMessage(t, response.Body.String())
  1270. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1271. // User stats
  1272. response = request(t, s, "GET", "/v1/account", "", nil)
  1273. require.Equal(t, 200, response.Code)
  1274. account, err := util.UnmarshalJSON[apiAccountResponse](io.NopCloser(response.Body))
  1275. require.Nil(t, err)
  1276. require.Equal(t, int64(5000), account.Limits.AttachmentFileSize)
  1277. require.Equal(t, int64(6000), account.Limits.AttachmentTotalSize)
  1278. require.Equal(t, int64(4999), account.Stats.AttachmentTotalSize)
  1279. require.Equal(t, int64(1001), account.Stats.AttachmentTotalSizeRemaining)
  1280. require.Equal(t, int64(1), account.Stats.Messages)
  1281. }
  1282. func TestServer_Visitor_XForwardedFor_None(t *testing.T) {
  1283. c := newTestConfig(t)
  1284. c.BehindProxy = true
  1285. s := newTestServer(t, c)
  1286. r, _ := http.NewRequest("GET", "/bla", nil)
  1287. r.RemoteAddr = "8.9.10.11"
  1288. r.Header.Set("X-Forwarded-For", " ") // Spaces, not empty!
  1289. v, err := s.visitor(r)
  1290. require.Nil(t, err)
  1291. require.Equal(t, "8.9.10.11", v.ip.String())
  1292. }
  1293. func TestServer_Visitor_XForwardedFor_Single(t *testing.T) {
  1294. c := newTestConfig(t)
  1295. c.BehindProxy = true
  1296. s := newTestServer(t, c)
  1297. r, _ := http.NewRequest("GET", "/bla", nil)
  1298. r.RemoteAddr = "8.9.10.11"
  1299. r.Header.Set("X-Forwarded-For", "1.1.1.1")
  1300. v, err := s.visitor(r)
  1301. require.Nil(t, err)
  1302. require.Equal(t, "1.1.1.1", v.ip.String())
  1303. }
  1304. func TestServer_Visitor_XForwardedFor_Multiple(t *testing.T) {
  1305. c := newTestConfig(t)
  1306. c.BehindProxy = true
  1307. s := newTestServer(t, c)
  1308. r, _ := http.NewRequest("GET", "/bla", nil)
  1309. r.RemoteAddr = "8.9.10.11"
  1310. r.Header.Set("X-Forwarded-For", "1.2.3.4 , 2.4.4.2,234.5.2.1 ")
  1311. v, err := s.visitor(r)
  1312. require.Nil(t, err)
  1313. require.Equal(t, "234.5.2.1", v.ip.String())
  1314. }
  1315. func TestServer_PublishWhileUpdatingStatsWithLotsOfMessages(t *testing.T) {
  1316. count := 50000
  1317. c := newTestConfig(t)
  1318. c.TotalTopicLimit = 50001
  1319. c.CacheStartupQueries = "pragma journal_mode = WAL; pragma synchronous = normal; pragma temp_store = memory;"
  1320. s := newTestServer(t, c)
  1321. // Add lots of messages
  1322. log.Printf("Adding %d messages", count)
  1323. start := time.Now()
  1324. messages := make([]*message, 0)
  1325. for i := 0; i < count; i++ {
  1326. topicID := fmt.Sprintf("topic%d", i)
  1327. _, err := s.topicsFromIDs(topicID) // Add topic to internal s.topics array
  1328. require.Nil(t, err)
  1329. messages = append(messages, newDefaultMessage(topicID, "some message"))
  1330. }
  1331. require.Nil(t, s.messageCache.addMessages(messages))
  1332. log.Printf("Done: Adding %d messages; took %s", count, time.Since(start).Round(time.Millisecond))
  1333. // Update stats
  1334. statsChan := make(chan bool)
  1335. go func() {
  1336. log.Printf("Updating stats")
  1337. start := time.Now()
  1338. s.execManager()
  1339. log.Printf("Done: Updating stats; took %s", time.Since(start).Round(time.Millisecond))
  1340. statsChan <- true
  1341. }()
  1342. time.Sleep(50 * time.Millisecond) // Make sure it starts first
  1343. // Publish message (during stats update)
  1344. log.Printf("Publishing message")
  1345. start = time.Now()
  1346. response := request(t, s, "PUT", "/mytopic", "some body", nil)
  1347. m := toMessage(t, response.Body.String())
  1348. assert.Equal(t, "some body", m.Message)
  1349. assert.True(t, time.Since(start) < 100*time.Millisecond)
  1350. log.Printf("Done: Publishing message; took %s", time.Since(start).Round(time.Millisecond))
  1351. // Wait for all goroutines
  1352. <-statsChan
  1353. log.Printf("Done: Waiting for all locks")
  1354. }
  1355. func newTestConfig(t *testing.T) *Config {
  1356. conf := NewConfig()
  1357. conf.BaseURL = "http://127.0.0.1:12345"
  1358. conf.CacheFile = filepath.Join(t.TempDir(), "cache.db")
  1359. conf.AttachmentCacheDir = t.TempDir()
  1360. return conf
  1361. }
  1362. func newTestConfigWithAuthFile(t *testing.T) *Config {
  1363. conf := newTestConfig(t)
  1364. conf.AuthFile = filepath.Join(t.TempDir(), "user.db")
  1365. return conf
  1366. }
  1367. func newTestServer(t *testing.T, config *Config) *Server {
  1368. server, err := New(config)
  1369. if err != nil {
  1370. t.Fatal(err)
  1371. }
  1372. return server
  1373. }
  1374. func request(t *testing.T, s *Server, method, url, body string, headers map[string]string) *httptest.ResponseRecorder {
  1375. rr := httptest.NewRecorder()
  1376. req, err := http.NewRequest(method, url, strings.NewReader(body))
  1377. if err != nil {
  1378. t.Fatal(err)
  1379. }
  1380. req.RemoteAddr = "9.9.9.9" // Used for tests
  1381. for k, v := range headers {
  1382. req.Header.Set(k, v)
  1383. }
  1384. s.handle(rr, req)
  1385. return rr
  1386. }
  1387. func subscribe(t *testing.T, s *Server, url string, rr *httptest.ResponseRecorder) context.CancelFunc {
  1388. ctx, cancel := context.WithCancel(context.Background())
  1389. req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
  1390. if err != nil {
  1391. t.Fatal(err)
  1392. }
  1393. done := make(chan bool)
  1394. go func() {
  1395. s.handle(rr, req)
  1396. done <- true
  1397. }()
  1398. cancelAndWaitForDone := func() {
  1399. time.Sleep(100 * time.Millisecond)
  1400. cancel()
  1401. <-done
  1402. }
  1403. time.Sleep(100 * time.Millisecond)
  1404. return cancelAndWaitForDone
  1405. }
  1406. func toMessages(t *testing.T, s string) []*message {
  1407. messages := make([]*message, 0)
  1408. scanner := bufio.NewScanner(strings.NewReader(s))
  1409. for scanner.Scan() {
  1410. messages = append(messages, toMessage(t, scanner.Text()))
  1411. }
  1412. return messages
  1413. }
  1414. func toMessage(t *testing.T, s string) *message {
  1415. var m message
  1416. require.Nil(t, json.NewDecoder(strings.NewReader(s)).Decode(&m))
  1417. return &m
  1418. }
  1419. func toHTTPError(t *testing.T, s string) *errHTTP {
  1420. var e errHTTP
  1421. require.Nil(t, json.NewDecoder(strings.NewReader(s)).Decode(&e))
  1422. return &e
  1423. }
  1424. func readAll(t *testing.T, rc io.ReadCloser) string {
  1425. b, err := io.ReadAll(rc)
  1426. if err != nil {
  1427. t.Fatal(err)
  1428. }
  1429. return string(b)
  1430. }