server_test.go 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180
  1. package server
  2. import (
  3. "bufio"
  4. "context"
  5. "encoding/base64"
  6. "encoding/json"
  7. "fmt"
  8. "github.com/stretchr/testify/require"
  9. "heckel.io/ntfy/auth"
  10. "heckel.io/ntfy/util"
  11. "math/rand"
  12. "net/http"
  13. "net/http/httptest"
  14. "os"
  15. "path/filepath"
  16. "strings"
  17. "sync"
  18. "testing"
  19. "time"
  20. )
  21. func TestServer_PublishAndPoll(t *testing.T) {
  22. s := newTestServer(t, newTestConfig(t))
  23. response1 := request(t, s, "PUT", "/mytopic", "my first message", nil)
  24. msg1 := toMessage(t, response1.Body.String())
  25. require.NotEmpty(t, msg1.ID)
  26. require.Equal(t, "my first message", msg1.Message)
  27. response2 := request(t, s, "PUT", "/mytopic", "my second\n\nmessage", nil)
  28. msg2 := toMessage(t, response2.Body.String())
  29. require.NotEqual(t, msg1.ID, msg2.ID)
  30. require.NotEmpty(t, msg2.ID)
  31. require.Equal(t, "my second\n\nmessage", msg2.Message)
  32. response := request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  33. messages := toMessages(t, response.Body.String())
  34. require.Equal(t, 2, len(messages))
  35. require.Equal(t, "my first message", messages[0].Message)
  36. require.Equal(t, "my second\n\nmessage", messages[1].Message)
  37. response = request(t, s, "GET", "/mytopic/sse?poll=1&since=all", "", nil)
  38. lines := strings.Split(strings.TrimSpace(response.Body.String()), "\n")
  39. require.Equal(t, 3, len(lines))
  40. require.Equal(t, "my first message", toMessage(t, strings.TrimPrefix(lines[0], "data: ")).Message)
  41. require.Equal(t, "", lines[1])
  42. require.Equal(t, "my second\n\nmessage", toMessage(t, strings.TrimPrefix(lines[2], "data: ")).Message)
  43. response = request(t, s, "GET", "/mytopic/raw?poll=1", "", nil)
  44. lines = strings.Split(strings.TrimSpace(response.Body.String()), "\n")
  45. require.Equal(t, 2, len(lines))
  46. require.Equal(t, "my first message", lines[0])
  47. require.Equal(t, "my second message", lines[1]) // \n -> " "
  48. }
  49. func TestServer_SubscribeOpenAndKeepalive(t *testing.T) {
  50. c := newTestConfig(t)
  51. c.KeepaliveInterval = time.Second
  52. s := newTestServer(t, c)
  53. rr := httptest.NewRecorder()
  54. ctx, cancel := context.WithCancel(context.Background())
  55. req, err := http.NewRequestWithContext(ctx, "GET", "/mytopic/json", nil)
  56. if err != nil {
  57. t.Fatal(err)
  58. }
  59. doneChan := make(chan bool)
  60. go func() {
  61. s.handle(rr, req)
  62. doneChan <- true
  63. }()
  64. time.Sleep(1300 * time.Millisecond)
  65. cancel()
  66. <-doneChan
  67. messages := toMessages(t, rr.Body.String())
  68. require.Equal(t, 2, len(messages))
  69. require.Equal(t, openEvent, messages[0].Event)
  70. require.Equal(t, "mytopic", messages[0].Topic)
  71. require.Equal(t, "", messages[0].Message)
  72. require.Equal(t, "", messages[0].Title)
  73. require.Equal(t, 0, messages[0].Priority)
  74. require.Nil(t, messages[0].Tags)
  75. require.Equal(t, keepaliveEvent, messages[1].Event)
  76. require.Equal(t, "mytopic", messages[1].Topic)
  77. require.Equal(t, "", messages[1].Message)
  78. require.Equal(t, "", messages[1].Title)
  79. require.Equal(t, 0, messages[1].Priority)
  80. require.Nil(t, messages[1].Tags)
  81. }
  82. func TestServer_PublishAndSubscribe(t *testing.T) {
  83. s := newTestServer(t, newTestConfig(t))
  84. subscribeRR := httptest.NewRecorder()
  85. subscribeCancel := subscribe(t, s, "/mytopic/json", subscribeRR)
  86. publishFirstRR := request(t, s, "PUT", "/mytopic", "my first message", nil)
  87. require.Equal(t, 200, publishFirstRR.Code)
  88. publishSecondRR := request(t, s, "PUT", "/mytopic", "my other message", map[string]string{
  89. "Title": " This is a title ",
  90. "X-Tags": "tag1,tag 2, tag3",
  91. "p": "1",
  92. })
  93. require.Equal(t, 200, publishSecondRR.Code)
  94. subscribeCancel()
  95. messages := toMessages(t, subscribeRR.Body.String())
  96. require.Equal(t, 3, len(messages))
  97. require.Equal(t, openEvent, messages[0].Event)
  98. require.Equal(t, messageEvent, messages[1].Event)
  99. require.Equal(t, "mytopic", messages[1].Topic)
  100. require.Equal(t, "my first message", messages[1].Message)
  101. require.Equal(t, "", messages[1].Title)
  102. require.Equal(t, 0, messages[1].Priority)
  103. require.Nil(t, messages[1].Tags)
  104. require.Equal(t, messageEvent, messages[2].Event)
  105. require.Equal(t, "mytopic", messages[2].Topic)
  106. require.Equal(t, "my other message", messages[2].Message)
  107. require.Equal(t, "This is a title", messages[2].Title)
  108. require.Equal(t, 1, messages[2].Priority)
  109. require.Equal(t, []string{"tag1", "tag 2", "tag3"}, messages[2].Tags)
  110. }
  111. func TestServer_StaticSites(t *testing.T) {
  112. s := newTestServer(t, newTestConfig(t))
  113. rr := request(t, s, "GET", "/", "", nil)
  114. require.Equal(t, 200, rr.Code)
  115. require.Contains(t, rr.Body.String(), "</html>")
  116. rr = request(t, s, "HEAD", "/", "", nil)
  117. require.Equal(t, 200, rr.Code)
  118. rr = request(t, s, "OPTIONS", "/", "", nil)
  119. require.Equal(t, 200, rr.Code)
  120. rr = request(t, s, "GET", "/does-not-exist.txt", "", nil)
  121. require.Equal(t, 404, rr.Code)
  122. rr = request(t, s, "GET", "/mytopic", "", nil)
  123. require.Equal(t, 200, rr.Code)
  124. require.Contains(t, rr.Body.String(), `<meta name="robots" content="noindex, nofollow"/>`)
  125. rr = request(t, s, "GET", "/static/css/home.css", "", nil)
  126. require.Equal(t, 200, rr.Code)
  127. require.Contains(t, rr.Body.String(), `html, body {`)
  128. rr = request(t, s, "GET", "/docs", "", nil)
  129. require.Equal(t, 301, rr.Code)
  130. // Docs test removed, it was failing annoyingly.
  131. rr = request(t, s, "GET", "/example.html", "", nil)
  132. require.Equal(t, 200, rr.Code)
  133. require.Contains(t, rr.Body.String(), "</html>")
  134. }
  135. func TestServer_PublishLargeMessage(t *testing.T) {
  136. c := newTestConfig(t)
  137. c.AttachmentCacheDir = "" // Disable attachments
  138. s := newTestServer(t, c)
  139. body := strings.Repeat("this is a large message", 5000)
  140. response := request(t, s, "PUT", "/mytopic", body, nil)
  141. require.Equal(t, 400, response.Code)
  142. }
  143. func TestServer_PublishPriority(t *testing.T) {
  144. s := newTestServer(t, newTestConfig(t))
  145. for prio := 1; prio <= 5; prio++ {
  146. response := request(t, s, "GET", fmt.Sprintf("/mytopic/publish?priority=%d", prio), fmt.Sprintf("priority %d", prio), nil)
  147. msg := toMessage(t, response.Body.String())
  148. require.Equal(t, prio, msg.Priority)
  149. }
  150. response := request(t, s, "GET", "/mytopic/publish?priority=min", "test", nil)
  151. require.Equal(t, 1, toMessage(t, response.Body.String()).Priority)
  152. response = request(t, s, "GET", "/mytopic/send?priority=low", "test", nil)
  153. require.Equal(t, 2, toMessage(t, response.Body.String()).Priority)
  154. response = request(t, s, "GET", "/mytopic/send?priority=default", "test", nil)
  155. require.Equal(t, 3, toMessage(t, response.Body.String()).Priority)
  156. response = request(t, s, "GET", "/mytopic/send?priority=high", "test", nil)
  157. require.Equal(t, 4, toMessage(t, response.Body.String()).Priority)
  158. response = request(t, s, "GET", "/mytopic/send?priority=max", "test", nil)
  159. require.Equal(t, 5, toMessage(t, response.Body.String()).Priority)
  160. response = request(t, s, "GET", "/mytopic/trigger?priority=urgent", "test", nil)
  161. require.Equal(t, 5, toMessage(t, response.Body.String()).Priority)
  162. response = request(t, s, "GET", "/mytopic/trigger?priority=INVALID", "test", nil)
  163. require.Equal(t, 40007, toHTTPError(t, response.Body.String()).Code)
  164. }
  165. func TestServer_PublishNoCache(t *testing.T) {
  166. s := newTestServer(t, newTestConfig(t))
  167. response := request(t, s, "PUT", "/mytopic", "this message is not cached", map[string]string{
  168. "Cache": "no",
  169. })
  170. msg := toMessage(t, response.Body.String())
  171. require.NotEmpty(t, msg.ID)
  172. require.Equal(t, "this message is not cached", msg.Message)
  173. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  174. messages := toMessages(t, response.Body.String())
  175. require.Empty(t, messages)
  176. }
  177. func TestServer_PublishAt(t *testing.T) {
  178. c := newTestConfig(t)
  179. c.MinDelay = time.Second
  180. c.AtSenderInterval = 100 * time.Millisecond
  181. s := newTestServer(t, c)
  182. response := request(t, s, "PUT", "/mytopic", "a message", map[string]string{
  183. "In": "1s",
  184. })
  185. require.Equal(t, 200, response.Code)
  186. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  187. messages := toMessages(t, response.Body.String())
  188. require.Equal(t, 0, len(messages))
  189. time.Sleep(time.Second)
  190. require.Nil(t, s.sendDelayedMessages())
  191. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  192. messages = toMessages(t, response.Body.String())
  193. require.Equal(t, 1, len(messages))
  194. require.Equal(t, "a message", messages[0].Message)
  195. }
  196. func TestServer_PublishAtWithCacheError(t *testing.T) {
  197. s := newTestServer(t, newTestConfig(t))
  198. response := request(t, s, "PUT", "/mytopic", "a message", map[string]string{
  199. "Cache": "no",
  200. "In": "30 min",
  201. })
  202. require.Equal(t, 400, response.Code)
  203. require.Equal(t, errHTTPBadRequestDelayNoCache, toHTTPError(t, response.Body.String()))
  204. }
  205. func TestServer_PublishAtTooShortDelay(t *testing.T) {
  206. s := newTestServer(t, newTestConfig(t))
  207. response := request(t, s, "PUT", "/mytopic", "a message", map[string]string{
  208. "In": "1s",
  209. })
  210. require.Equal(t, 400, response.Code)
  211. }
  212. func TestServer_PublishAtTooLongDelay(t *testing.T) {
  213. s := newTestServer(t, newTestConfig(t))
  214. response := request(t, s, "PUT", "/mytopic", "a message", map[string]string{
  215. "In": "99999999h",
  216. })
  217. require.Equal(t, 400, response.Code)
  218. }
  219. func TestServer_PublishAtInvalidDelay(t *testing.T) {
  220. s := newTestServer(t, newTestConfig(t))
  221. response := request(t, s, "PUT", "/mytopic?delay=INVALID", "a message", nil)
  222. err := toHTTPError(t, response.Body.String())
  223. require.Equal(t, 400, response.Code)
  224. require.Equal(t, 40004, err.Code)
  225. }
  226. func TestServer_PublishAtTooLarge(t *testing.T) {
  227. s := newTestServer(t, newTestConfig(t))
  228. response := request(t, s, "PUT", "/mytopic?x-in=99999h", "a message", nil)
  229. err := toHTTPError(t, response.Body.String())
  230. require.Equal(t, 400, response.Code)
  231. require.Equal(t, 40006, err.Code)
  232. }
  233. func TestServer_PublishAtAndPrune(t *testing.T) {
  234. s := newTestServer(t, newTestConfig(t))
  235. response := request(t, s, "PUT", "/mytopic", "a message", map[string]string{
  236. "In": "1h",
  237. })
  238. require.Equal(t, 200, response.Code)
  239. s.updateStatsAndPrune() // Fire pruning
  240. response = request(t, s, "GET", "/mytopic/json?poll=1&scheduled=1", "", nil)
  241. messages := toMessages(t, response.Body.String())
  242. require.Equal(t, 1, len(messages)) // Not affected by pruning
  243. require.Equal(t, "a message", messages[0].Message)
  244. }
  245. func TestServer_PublishAndMultiPoll(t *testing.T) {
  246. s := newTestServer(t, newTestConfig(t))
  247. response := request(t, s, "PUT", "/mytopic1", "message 1", nil)
  248. msg := toMessage(t, response.Body.String())
  249. require.NotEmpty(t, msg.ID)
  250. require.Equal(t, "mytopic1", msg.Topic)
  251. require.Equal(t, "message 1", msg.Message)
  252. response = request(t, s, "PUT", "/mytopic2", "message 2", nil)
  253. msg = toMessage(t, response.Body.String())
  254. require.NotEmpty(t, msg.ID)
  255. require.Equal(t, "mytopic2", msg.Topic)
  256. require.Equal(t, "message 2", msg.Message)
  257. response = request(t, s, "GET", "/mytopic1/json?poll=1", "", nil)
  258. messages := toMessages(t, response.Body.String())
  259. require.Equal(t, 1, len(messages))
  260. require.Equal(t, "mytopic1", messages[0].Topic)
  261. require.Equal(t, "message 1", messages[0].Message)
  262. response = request(t, s, "GET", "/mytopic1,mytopic2/json?poll=1", "", nil)
  263. messages = toMessages(t, response.Body.String())
  264. require.Equal(t, 2, len(messages))
  265. require.Equal(t, "mytopic1", messages[0].Topic)
  266. require.Equal(t, "message 1", messages[0].Message)
  267. require.Equal(t, "mytopic2", messages[1].Topic)
  268. require.Equal(t, "message 2", messages[1].Message)
  269. }
  270. func TestServer_PublishWithNopCache(t *testing.T) {
  271. c := newTestConfig(t)
  272. c.CacheDuration = 0
  273. s := newTestServer(t, c)
  274. subscribeRR := httptest.NewRecorder()
  275. subscribeCancel := subscribe(t, s, "/mytopic/json", subscribeRR)
  276. publishRR := request(t, s, "PUT", "/mytopic", "my first message", nil)
  277. require.Equal(t, 200, publishRR.Code)
  278. subscribeCancel()
  279. messages := toMessages(t, subscribeRR.Body.String())
  280. require.Equal(t, 2, len(messages))
  281. require.Equal(t, openEvent, messages[0].Event)
  282. require.Equal(t, messageEvent, messages[1].Event)
  283. require.Equal(t, "my first message", messages[1].Message)
  284. response := request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  285. messages = toMessages(t, response.Body.String())
  286. require.Empty(t, messages)
  287. }
  288. func TestServer_PublishAndPollSince(t *testing.T) {
  289. s := newTestServer(t, newTestConfig(t))
  290. request(t, s, "PUT", "/mytopic", "test 1", nil)
  291. time.Sleep(1100 * time.Millisecond)
  292. since := time.Now().Unix()
  293. request(t, s, "PUT", "/mytopic", "test 2", nil)
  294. response := request(t, s, "GET", fmt.Sprintf("/mytopic/json?poll=1&since=%d", since), "", nil)
  295. messages := toMessages(t, response.Body.String())
  296. require.Equal(t, 1, len(messages))
  297. require.Equal(t, "test 2", messages[0].Message)
  298. response = request(t, s, "GET", "/mytopic/json?poll=1&since=10s", "", nil)
  299. messages = toMessages(t, response.Body.String())
  300. require.Equal(t, 2, len(messages))
  301. require.Equal(t, "test 1", messages[0].Message)
  302. response = request(t, s, "GET", "/mytopic/json?poll=1&since=100ms", "", nil)
  303. messages = toMessages(t, response.Body.String())
  304. require.Equal(t, 1, len(messages))
  305. require.Equal(t, "test 2", messages[0].Message)
  306. response = request(t, s, "GET", "/mytopic/json?poll=1&since=INVALID", "", nil)
  307. require.Equal(t, 40008, toHTTPError(t, response.Body.String()).Code)
  308. }
  309. func TestServer_PublishViaGET(t *testing.T) {
  310. s := newTestServer(t, newTestConfig(t))
  311. response := request(t, s, "GET", "/mytopic/trigger", "", nil)
  312. msg := toMessage(t, response.Body.String())
  313. require.NotEmpty(t, msg.ID)
  314. require.Equal(t, "triggered", msg.Message)
  315. 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)
  316. msg = toMessage(t, response.Body.String())
  317. require.NotEmpty(t, msg.ID)
  318. require.Equal(t, "This is a test", msg.Message)
  319. require.Equal(t, "This is a title", msg.Title)
  320. require.Equal(t, []string{"skull"}, msg.Tags)
  321. require.Equal(t, 5, msg.Priority)
  322. require.Greater(t, msg.Time, time.Now().Add(23*time.Hour).Unix())
  323. }
  324. func TestServer_PublishMessageInHeaderWithNewlines(t *testing.T) {
  325. s := newTestServer(t, newTestConfig(t))
  326. response := request(t, s, "PUT", "/mytopic", "", map[string]string{
  327. "Message": "Line 1\\nLine 2",
  328. })
  329. msg := toMessage(t, response.Body.String())
  330. require.NotEmpty(t, msg.ID)
  331. require.Equal(t, "Line 1\nLine 2", msg.Message) // \\n -> \n !
  332. }
  333. func TestServer_PublishFirebase(t *testing.T) {
  334. // This is unfortunately not much of a test, since it merely fires the messages towards Firebase,
  335. // but cannot re-read them. There is no way from Go to read the messages back, or even get an error back.
  336. // I tried everything. I already had written the test, and it increases the code coverage, so I'll leave it ... :shrug: ...
  337. c := newTestConfig(t)
  338. c.FirebaseKeyFile = firebaseServiceAccountFile(t) // May skip the test!
  339. s := newTestServer(t, c)
  340. // Normal message
  341. response := request(t, s, "PUT", "/mytopic", "This is a message for firebase", nil)
  342. msg := toMessage(t, response.Body.String())
  343. require.NotEmpty(t, msg.ID)
  344. // Keepalive message
  345. require.Nil(t, s.firebase(newKeepaliveMessage(firebaseControlTopic)))
  346. time.Sleep(500 * time.Millisecond) // Time for sends
  347. }
  348. func TestServer_PublishInvalidTopic(t *testing.T) {
  349. s := newTestServer(t, newTestConfig(t))
  350. s.mailer = &testMailer{}
  351. response := request(t, s, "PUT", "/docs", "fail", nil)
  352. require.Equal(t, 40010, toHTTPError(t, response.Body.String()).Code)
  353. }
  354. func TestServer_PollWithQueryFilters(t *testing.T) {
  355. s := newTestServer(t, newTestConfig(t))
  356. response := request(t, s, "PUT", "/mytopic?priority=1&tags=tag1,tag2", "my first message", nil)
  357. msg := toMessage(t, response.Body.String())
  358. require.NotEmpty(t, msg.ID)
  359. response = request(t, s, "PUT", "/mytopic?title=a+title", "my second message", map[string]string{
  360. "Tags": "tag2,tag3",
  361. })
  362. msg = toMessage(t, response.Body.String())
  363. require.NotEmpty(t, msg.ID)
  364. queriesThatShouldReturnMessageOne := []string{
  365. "/mytopic/json?poll=1&priority=1",
  366. "/mytopic/json?poll=1&priority=min",
  367. "/mytopic/json?poll=1&priority=min,low",
  368. "/mytopic/json?poll=1&priority=1,2",
  369. "/mytopic/json?poll=1&p=2,min",
  370. "/mytopic/json?poll=1&tags=tag1",
  371. "/mytopic/json?poll=1&tags=tag1,tag2",
  372. "/mytopic/json?poll=1&message=my+first+message",
  373. }
  374. for _, query := range queriesThatShouldReturnMessageOne {
  375. response = request(t, s, "GET", query, "", nil)
  376. messages := toMessages(t, response.Body.String())
  377. require.Equal(t, 1, len(messages), "Query failed: "+query)
  378. require.Equal(t, "my first message", messages[0].Message, "Query failed: "+query)
  379. }
  380. queriesThatShouldReturnMessageTwo := []string{
  381. "/mytopic/json?poll=1&x-priority=3", // !
  382. "/mytopic/json?poll=1&priority=3",
  383. "/mytopic/json?poll=1&priority=default",
  384. "/mytopic/json?poll=1&p=3",
  385. "/mytopic/json?poll=1&x-tags=tag2,tag3",
  386. "/mytopic/json?poll=1&tags=tag2,tag3",
  387. "/mytopic/json?poll=1&tag=tag2,tag3",
  388. "/mytopic/json?poll=1&ta=tag2,tag3",
  389. "/mytopic/json?poll=1&x-title=a+title",
  390. "/mytopic/json?poll=1&title=a+title",
  391. "/mytopic/json?poll=1&t=a+title",
  392. "/mytopic/json?poll=1&x-message=my+second+message",
  393. "/mytopic/json?poll=1&message=my+second+message",
  394. "/mytopic/json?poll=1&m=my+second+message",
  395. "/mytopic/json?x-poll=1&m=my+second+message",
  396. "/mytopic/json?po=1&m=my+second+message",
  397. }
  398. for _, query := range queriesThatShouldReturnMessageTwo {
  399. response = request(t, s, "GET", query, "", nil)
  400. messages := toMessages(t, response.Body.String())
  401. require.Equal(t, 1, len(messages), "Query failed: "+query)
  402. require.Equal(t, "my second message", messages[0].Message, "Query failed: "+query)
  403. }
  404. queriesThatShouldReturnNoMessages := []string{
  405. "/mytopic/json?poll=1&priority=4",
  406. "/mytopic/json?poll=1&tags=tag1,tag2,tag3",
  407. "/mytopic/json?poll=1&title=another+title",
  408. "/mytopic/json?poll=1&message=my+third+message",
  409. "/mytopic/json?poll=1&message=my+third+message",
  410. }
  411. for _, query := range queriesThatShouldReturnNoMessages {
  412. response = request(t, s, "GET", query, "", nil)
  413. messages := toMessages(t, response.Body.String())
  414. require.Equal(t, 0, len(messages), "Query failed: "+query)
  415. }
  416. }
  417. func TestServer_SubscribeWithQueryFilters(t *testing.T) {
  418. c := newTestConfig(t)
  419. c.KeepaliveInterval = 800 * time.Millisecond
  420. s := newTestServer(t, c)
  421. subscribeResponse := httptest.NewRecorder()
  422. subscribeCancel := subscribe(t, s, "/mytopic/json?tags=zfs-issue", subscribeResponse)
  423. response := request(t, s, "PUT", "/mytopic", "my first message", nil)
  424. require.Equal(t, 200, response.Code)
  425. response = request(t, s, "PUT", "/mytopic", "ZFS scrub failed", map[string]string{
  426. "Tags": "zfs-issue,zfs-scrub",
  427. })
  428. require.Equal(t, 200, response.Code)
  429. time.Sleep(850 * time.Millisecond)
  430. subscribeCancel()
  431. messages := toMessages(t, subscribeResponse.Body.String())
  432. require.Equal(t, 3, len(messages))
  433. require.Equal(t, openEvent, messages[0].Event)
  434. require.Equal(t, messageEvent, messages[1].Event)
  435. require.Equal(t, "ZFS scrub failed", messages[1].Message)
  436. require.Equal(t, keepaliveEvent, messages[2].Event)
  437. }
  438. func TestServer_Auth_Success_Admin(t *testing.T) {
  439. c := newTestConfig(t)
  440. c.AuthFile = filepath.Join(t.TempDir(), "user.db")
  441. s := newTestServer(t, c)
  442. manager := s.auth.(auth.Manager)
  443. require.Nil(t, manager.AddUser("phil", "phil", auth.RoleAdmin))
  444. response := request(t, s, "GET", "/mytopic/auth", "", map[string]string{
  445. "Authorization": basicAuth("phil:phil"),
  446. })
  447. require.Equal(t, 200, response.Code)
  448. require.Equal(t, `{"success":true}`+"\n", response.Body.String())
  449. }
  450. func TestServer_Auth_Success_User(t *testing.T) {
  451. c := newTestConfig(t)
  452. c.AuthFile = filepath.Join(t.TempDir(), "user.db")
  453. c.AuthDefaultRead = false
  454. c.AuthDefaultWrite = false
  455. s := newTestServer(t, c)
  456. manager := s.auth.(auth.Manager)
  457. require.Nil(t, manager.AddUser("ben", "ben", auth.RoleUser))
  458. require.Nil(t, manager.AllowAccess("ben", "mytopic", true, true))
  459. response := request(t, s, "GET", "/mytopic/auth", "", map[string]string{
  460. "Authorization": basicAuth("ben:ben"),
  461. })
  462. require.Equal(t, 200, response.Code)
  463. }
  464. func TestServer_Auth_Success_User_MultipleTopics(t *testing.T) {
  465. c := newTestConfig(t)
  466. c.AuthFile = filepath.Join(t.TempDir(), "user.db")
  467. c.AuthDefaultRead = false
  468. c.AuthDefaultWrite = false
  469. s := newTestServer(t, c)
  470. manager := s.auth.(auth.Manager)
  471. require.Nil(t, manager.AddUser("ben", "ben", auth.RoleUser))
  472. require.Nil(t, manager.AllowAccess("ben", "mytopic", true, true))
  473. require.Nil(t, manager.AllowAccess("ben", "anothertopic", true, true))
  474. response := request(t, s, "GET", "/mytopic,anothertopic/auth", "", map[string]string{
  475. "Authorization": basicAuth("ben:ben"),
  476. })
  477. require.Equal(t, 200, response.Code)
  478. response = request(t, s, "GET", "/mytopic,anothertopic,NOT-THIS-ONE/auth", "", map[string]string{
  479. "Authorization": basicAuth("ben:ben"),
  480. })
  481. require.Equal(t, 403, response.Code)
  482. }
  483. func TestServer_Auth_Fail_InvalidPass(t *testing.T) {
  484. c := newTestConfig(t)
  485. c.AuthFile = filepath.Join(t.TempDir(), "user.db")
  486. c.AuthDefaultRead = false
  487. c.AuthDefaultWrite = false
  488. s := newTestServer(t, c)
  489. manager := s.auth.(auth.Manager)
  490. require.Nil(t, manager.AddUser("phil", "phil", auth.RoleAdmin))
  491. response := request(t, s, "GET", "/mytopic/auth", "", map[string]string{
  492. "Authorization": basicAuth("phil:INVALID"),
  493. })
  494. require.Equal(t, 401, response.Code)
  495. }
  496. func TestServer_Auth_Fail_Unauthorized(t *testing.T) {
  497. c := newTestConfig(t)
  498. c.AuthFile = filepath.Join(t.TempDir(), "user.db")
  499. c.AuthDefaultRead = false
  500. c.AuthDefaultWrite = false
  501. s := newTestServer(t, c)
  502. manager := s.auth.(auth.Manager)
  503. require.Nil(t, manager.AddUser("ben", "ben", auth.RoleUser))
  504. require.Nil(t, manager.AllowAccess("ben", "sometopic", true, true)) // Not mytopic!
  505. response := request(t, s, "GET", "/mytopic/auth", "", map[string]string{
  506. "Authorization": basicAuth("ben:ben"),
  507. })
  508. require.Equal(t, 403, response.Code)
  509. }
  510. func TestServer_Auth_Fail_CannotPublish(t *testing.T) {
  511. c := newTestConfig(t)
  512. c.AuthFile = filepath.Join(t.TempDir(), "user.db")
  513. c.AuthDefaultRead = true // Open by default
  514. c.AuthDefaultWrite = true // Open by default
  515. s := newTestServer(t, c)
  516. manager := s.auth.(auth.Manager)
  517. require.Nil(t, manager.AddUser("phil", "phil", auth.RoleAdmin))
  518. require.Nil(t, manager.AllowAccess(auth.Everyone, "private", false, false))
  519. require.Nil(t, manager.AllowAccess(auth.Everyone, "announcements", true, false))
  520. response := request(t, s, "PUT", "/mytopic", "test", nil)
  521. require.Equal(t, 200, response.Code)
  522. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  523. require.Equal(t, 200, response.Code)
  524. response = request(t, s, "PUT", "/announcements", "test", nil)
  525. require.Equal(t, 403, response.Code) // Cannot write as anonymous
  526. response = request(t, s, "PUT", "/announcements", "test", map[string]string{
  527. "Authorization": basicAuth("phil:phil"),
  528. })
  529. require.Equal(t, 200, response.Code)
  530. response = request(t, s, "GET", "/announcements/json?poll=1", "", nil)
  531. require.Equal(t, 200, response.Code) // Anonymous read allowed
  532. response = request(t, s, "GET", "/private/json?poll=1", "", nil)
  533. require.Equal(t, 403, response.Code) // Anonymous read not allowed
  534. }
  535. func TestServer_Auth_ViaQuery(t *testing.T) {
  536. c := newTestConfig(t)
  537. c.AuthFile = filepath.Join(t.TempDir(), "user.db")
  538. c.AuthDefaultRead = false
  539. c.AuthDefaultWrite = false
  540. s := newTestServer(t, c)
  541. manager := s.auth.(auth.Manager)
  542. require.Nil(t, manager.AddUser("ben", "some pass", auth.RoleAdmin))
  543. u := fmt.Sprintf("/mytopic/json?poll=1&auth=%s", base64.RawURLEncoding.EncodeToString([]byte(basicAuth("ben:some pass"))))
  544. response := request(t, s, "GET", u, "", nil)
  545. require.Equal(t, 200, response.Code)
  546. u = fmt.Sprintf("/mytopic/json?poll=1&auth=%s", base64.RawURLEncoding.EncodeToString([]byte(basicAuth("ben:WRONNNGGGG"))))
  547. response = request(t, s, "GET", u, "", nil)
  548. require.Equal(t, 401, response.Code)
  549. }
  550. /*
  551. func TestServer_Curl_Publish_Poll(t *testing.T) {
  552. s, port := test.StartServer(t)
  553. defer test.StopServer(t, s, port)
  554. cmd := exec.Command("sh", "-c", fmt.Sprintf(`curl -sd "This is a test" localhost:%d/mytopic`, port))
  555. require.Nil(t, cmd.Run())
  556. b, err := cmd.CombinedOutput()
  557. require.Nil(t, err)
  558. msg := toMessage(t, string(b))
  559. require.Equal(t, "This is a test", msg.Message)
  560. cmd = exec.Command("sh", "-c", fmt.Sprintf(`curl "localhost:%d/mytopic?poll=1"`, port))
  561. require.Nil(t, cmd.Run())
  562. b, err = cmd.CombinedOutput()
  563. require.Nil(t, err)
  564. msg = toMessage(t, string(b))
  565. require.Equal(t, "This is a test", msg.Message)
  566. }
  567. */
  568. type testMailer struct {
  569. count int
  570. mu sync.Mutex
  571. }
  572. func (t *testMailer) Send(from, to string, m *message) error {
  573. t.mu.Lock()
  574. defer t.mu.Unlock()
  575. t.count++
  576. return nil
  577. }
  578. func TestServer_PublishTooRequests_Defaults(t *testing.T) {
  579. s := newTestServer(t, newTestConfig(t))
  580. for i := 0; i < 60; i++ {
  581. response := request(t, s, "PUT", "/mytopic", fmt.Sprintf("message %d", i), nil)
  582. require.Equal(t, 200, response.Code)
  583. }
  584. response := request(t, s, "PUT", "/mytopic", "message", nil)
  585. require.Equal(t, 429, response.Code)
  586. }
  587. func TestServer_PublishTooRequests_Defaults_ExemptHosts(t *testing.T) {
  588. c := newTestConfig(t)
  589. c.VisitorRequestExemptIPAddrs = []string{"9.9.9.9"} // see request()
  590. s := newTestServer(t, c)
  591. for i := 0; i < 65; i++ { // > 60
  592. response := request(t, s, "PUT", "/mytopic", fmt.Sprintf("message %d", i), nil)
  593. require.Equal(t, 200, response.Code)
  594. }
  595. }
  596. func TestServer_PublishTooRequests_ShortReplenish(t *testing.T) {
  597. c := newTestConfig(t)
  598. c.VisitorRequestLimitBurst = 60
  599. c.VisitorRequestLimitReplenish = 500 * time.Millisecond
  600. s := newTestServer(t, c)
  601. for i := 0; i < 60; i++ {
  602. response := request(t, s, "PUT", "/mytopic", fmt.Sprintf("message %d", i), nil)
  603. require.Equal(t, 200, response.Code)
  604. }
  605. response := request(t, s, "PUT", "/mytopic", "message", nil)
  606. require.Equal(t, 429, response.Code)
  607. time.Sleep(510 * time.Millisecond)
  608. response = request(t, s, "PUT", "/mytopic", "message", nil)
  609. require.Equal(t, 200, response.Code)
  610. }
  611. func TestServer_PublishTooManyEmails_Defaults(t *testing.T) {
  612. s := newTestServer(t, newTestConfig(t))
  613. s.mailer = &testMailer{}
  614. for i := 0; i < 16; i++ {
  615. response := request(t, s, "PUT", "/mytopic", fmt.Sprintf("message %d", i), map[string]string{
  616. "E-Mail": "test@example.com",
  617. })
  618. require.Equal(t, 200, response.Code)
  619. }
  620. response := request(t, s, "PUT", "/mytopic", "one too many", map[string]string{
  621. "E-Mail": "test@example.com",
  622. })
  623. require.Equal(t, 429, response.Code)
  624. }
  625. func TestServer_PublishTooManyEmails_Replenish(t *testing.T) {
  626. c := newTestConfig(t)
  627. c.VisitorEmailLimitReplenish = 500 * time.Millisecond
  628. s := newTestServer(t, c)
  629. s.mailer = &testMailer{}
  630. for i := 0; i < 16; i++ {
  631. response := request(t, s, "PUT", "/mytopic", fmt.Sprintf("message %d", i), map[string]string{
  632. "E-Mail": "test@example.com",
  633. })
  634. require.Equal(t, 200, response.Code)
  635. }
  636. response := request(t, s, "PUT", "/mytopic", "one too many", map[string]string{
  637. "E-Mail": "test@example.com",
  638. })
  639. require.Equal(t, 429, response.Code)
  640. time.Sleep(510 * time.Millisecond)
  641. response = request(t, s, "PUT", "/mytopic", "this should be okay again too many", map[string]string{
  642. "E-Mail": "test@example.com",
  643. })
  644. require.Equal(t, 200, response.Code)
  645. response = request(t, s, "PUT", "/mytopic", "and bad again", map[string]string{
  646. "E-Mail": "test@example.com",
  647. })
  648. require.Equal(t, 429, response.Code)
  649. }
  650. func TestServer_PublishDelayedEmail_Fail(t *testing.T) {
  651. s := newTestServer(t, newTestConfig(t))
  652. s.mailer = &testMailer{}
  653. response := request(t, s, "PUT", "/mytopic", "fail", map[string]string{
  654. "E-Mail": "test@example.com",
  655. "Delay": "20 min",
  656. })
  657. require.Equal(t, 400, response.Code)
  658. }
  659. func TestServer_PublishEmailNoMailer_Fail(t *testing.T) {
  660. s := newTestServer(t, newTestConfig(t))
  661. response := request(t, s, "PUT", "/mytopic", "fail", map[string]string{
  662. "E-Mail": "test@example.com",
  663. })
  664. require.Equal(t, 400, response.Code)
  665. }
  666. func TestServer_UnifiedPushDiscovery(t *testing.T) {
  667. s := newTestServer(t, newTestConfig(t))
  668. response := request(t, s, "GET", "/mytopic?up=1", "", nil)
  669. require.Equal(t, 200, response.Code)
  670. require.Equal(t, `{"unifiedpush":{"version":1}}`+"\n", response.Body.String())
  671. }
  672. func TestServer_PublishUnifiedPushBinary_AndPoll(t *testing.T) {
  673. b := make([]byte, 12) // Max length
  674. _, err := rand.Read(b)
  675. require.Nil(t, err)
  676. s := newTestServer(t, newTestConfig(t))
  677. response := request(t, s, "PUT", "/mytopic?up=1", string(b), nil)
  678. require.Equal(t, 200, response.Code)
  679. m := toMessage(t, response.Body.String())
  680. require.Equal(t, "base64", m.Encoding)
  681. b2, err := base64.StdEncoding.DecodeString(m.Message)
  682. require.Nil(t, err)
  683. require.Equal(t, b, b2)
  684. response = request(t, s, "GET", "/mytopic/json?poll=1", string(b), nil)
  685. require.Equal(t, 200, response.Code)
  686. m = toMessage(t, response.Body.String())
  687. require.Equal(t, "base64", m.Encoding)
  688. b2, err = base64.StdEncoding.DecodeString(m.Message)
  689. require.Nil(t, err)
  690. require.Equal(t, b, b2)
  691. }
  692. func TestServer_PublishUnifiedPushBinary_Truncated(t *testing.T) {
  693. b := make([]byte, 5000) // Longer than max length
  694. _, err := rand.Read(b)
  695. require.Nil(t, err)
  696. s := newTestServer(t, newTestConfig(t))
  697. response := request(t, s, "PUT", "/mytopic?up=1", string(b), nil)
  698. require.Equal(t, 200, response.Code)
  699. m := toMessage(t, response.Body.String())
  700. require.Equal(t, "base64", m.Encoding)
  701. b2, err := base64.StdEncoding.DecodeString(m.Message)
  702. require.Nil(t, err)
  703. require.Equal(t, 4096, len(b2))
  704. require.Equal(t, b[:4096], b2)
  705. }
  706. func TestServer_PublishUnifiedPushText(t *testing.T) {
  707. s := newTestServer(t, newTestConfig(t))
  708. response := request(t, s, "PUT", "/mytopic?up=1", "this is a unifiedpush text message", nil)
  709. require.Equal(t, 200, response.Code)
  710. m := toMessage(t, response.Body.String())
  711. require.Equal(t, "", m.Encoding)
  712. require.Equal(t, "this is a unifiedpush text message", m.Message)
  713. }
  714. func TestServer_PublishAttachment(t *testing.T) {
  715. content := util.RandomString(5000) // > 4096
  716. s := newTestServer(t, newTestConfig(t))
  717. response := request(t, s, "PUT", "/mytopic", content, nil)
  718. msg := toMessage(t, response.Body.String())
  719. require.Equal(t, "attachment.txt", msg.Attachment.Name)
  720. require.Equal(t, "text/plain; charset=utf-8", msg.Attachment.Type)
  721. require.Equal(t, int64(5000), msg.Attachment.Size)
  722. require.GreaterOrEqual(t, msg.Attachment.Expires, time.Now().Add(179*time.Minute).Unix()) // Almost 3 hours
  723. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  724. require.Equal(t, "", msg.Attachment.Owner) // Should never be returned
  725. require.FileExists(t, filepath.Join(s.config.AttachmentCacheDir, msg.ID))
  726. path := strings.TrimPrefix(msg.Attachment.URL, "http://127.0.0.1:12345")
  727. response = request(t, s, "GET", path, "", nil)
  728. require.Equal(t, 200, response.Code)
  729. require.Equal(t, "5000", response.Header().Get("Content-Length"))
  730. require.Equal(t, content, response.Body.String())
  731. // Slightly unrelated cross-test: make sure we add an owner for internal attachments
  732. size, err := s.messageCache.AttachmentsSize("9.9.9.9") // See request()
  733. require.Nil(t, err)
  734. require.Equal(t, int64(5000), size)
  735. }
  736. func TestServer_PublishAttachmentShortWithFilename(t *testing.T) {
  737. c := newTestConfig(t)
  738. c.BehindProxy = true
  739. s := newTestServer(t, c)
  740. content := "this is an ATTACHMENT"
  741. response := request(t, s, "PUT", "/mytopic?f=myfile.txt", content, map[string]string{
  742. "X-Forwarded-For": "1.2.3.4",
  743. })
  744. msg := toMessage(t, response.Body.String())
  745. require.Equal(t, "myfile.txt", msg.Attachment.Name)
  746. require.Equal(t, "text/plain; charset=utf-8", msg.Attachment.Type)
  747. require.Equal(t, int64(21), msg.Attachment.Size)
  748. require.GreaterOrEqual(t, msg.Attachment.Expires, time.Now().Add(3*time.Hour).Unix())
  749. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  750. require.Equal(t, "", msg.Attachment.Owner) // Should never be returned
  751. require.FileExists(t, filepath.Join(s.config.AttachmentCacheDir, msg.ID))
  752. path := strings.TrimPrefix(msg.Attachment.URL, "http://127.0.0.1:12345")
  753. response = request(t, s, "GET", path, "", nil)
  754. require.Equal(t, 200, response.Code)
  755. require.Equal(t, "21", response.Header().Get("Content-Length"))
  756. require.Equal(t, content, response.Body.String())
  757. // Slightly unrelated cross-test: make sure we add an owner for internal attachments
  758. size, err := s.messageCache.AttachmentsSize("1.2.3.4")
  759. require.Nil(t, err)
  760. require.Equal(t, int64(21), size)
  761. }
  762. func TestServer_PublishAttachmentExternalWithoutFilename(t *testing.T) {
  763. s := newTestServer(t, newTestConfig(t))
  764. response := request(t, s, "PUT", "/mytopic", "", map[string]string{
  765. "Attach": "https://upload.wikimedia.org/wikipedia/commons/f/fd/Pink_flower.jpg",
  766. })
  767. msg := toMessage(t, response.Body.String())
  768. require.Equal(t, "You received a file: Pink_flower.jpg", msg.Message)
  769. require.Equal(t, "Pink_flower.jpg", msg.Attachment.Name)
  770. require.Equal(t, "https://upload.wikimedia.org/wikipedia/commons/f/fd/Pink_flower.jpg", msg.Attachment.URL)
  771. require.Equal(t, "", msg.Attachment.Type)
  772. require.Equal(t, int64(0), msg.Attachment.Size)
  773. require.Equal(t, int64(0), msg.Attachment.Expires)
  774. require.Equal(t, "", msg.Attachment.Owner)
  775. // Slightly unrelated cross-test: make sure we don't add an owner for external attachments
  776. size, err := s.messageCache.AttachmentsSize("127.0.0.1")
  777. require.Nil(t, err)
  778. require.Equal(t, int64(0), size)
  779. }
  780. func TestServer_PublishAttachmentExternalWithFilename(t *testing.T) {
  781. s := newTestServer(t, newTestConfig(t))
  782. response := request(t, s, "PUT", "/mytopic", "This is a custom message", map[string]string{
  783. "X-Attach": "https://upload.wikimedia.org/wikipedia/commons/f/fd/Pink_flower.jpg",
  784. "File": "some file.jpg",
  785. })
  786. msg := toMessage(t, response.Body.String())
  787. require.Equal(t, "This is a custom message", msg.Message)
  788. require.Equal(t, "some file.jpg", msg.Attachment.Name)
  789. require.Equal(t, "https://upload.wikimedia.org/wikipedia/commons/f/fd/Pink_flower.jpg", msg.Attachment.URL)
  790. require.Equal(t, "", msg.Attachment.Type)
  791. require.Equal(t, int64(0), msg.Attachment.Size)
  792. require.Equal(t, int64(0), msg.Attachment.Expires)
  793. require.Equal(t, "", msg.Attachment.Owner)
  794. }
  795. func TestServer_PublishAttachmentBadURL(t *testing.T) {
  796. s := newTestServer(t, newTestConfig(t))
  797. response := request(t, s, "PUT", "/mytopic?a=not+a+URL", "", nil)
  798. err := toHTTPError(t, response.Body.String())
  799. require.Equal(t, 400, response.Code)
  800. require.Equal(t, 400, err.HTTPCode)
  801. require.Equal(t, 40013, err.Code)
  802. }
  803. func TestServer_PublishAttachmentTooLargeContentLength(t *testing.T) {
  804. content := util.RandomString(5000) // > 4096
  805. s := newTestServer(t, newTestConfig(t))
  806. response := request(t, s, "PUT", "/mytopic", content, map[string]string{
  807. "Content-Length": "20000000",
  808. })
  809. err := toHTTPError(t, response.Body.String())
  810. require.Equal(t, 400, response.Code)
  811. require.Equal(t, 400, err.HTTPCode)
  812. require.Equal(t, 40012, err.Code)
  813. }
  814. func TestServer_PublishAttachmentTooLargeBodyAttachmentFileSizeLimit(t *testing.T) {
  815. content := util.RandomString(5001) // > 5000, see below
  816. c := newTestConfig(t)
  817. c.AttachmentFileSizeLimit = 5000
  818. s := newTestServer(t, c)
  819. response := request(t, s, "PUT", "/mytopic", content, nil)
  820. err := toHTTPError(t, response.Body.String())
  821. require.Equal(t, 400, response.Code)
  822. require.Equal(t, 400, err.HTTPCode)
  823. require.Equal(t, 40012, err.Code)
  824. }
  825. func TestServer_PublishAttachmentExpiryBeforeDelivery(t *testing.T) {
  826. c := newTestConfig(t)
  827. c.AttachmentExpiryDuration = 10 * time.Minute
  828. s := newTestServer(t, c)
  829. response := request(t, s, "PUT", "/mytopic", util.RandomString(5000), map[string]string{
  830. "Delay": "11 min", // > AttachmentExpiryDuration
  831. })
  832. err := toHTTPError(t, response.Body.String())
  833. require.Equal(t, 400, response.Code)
  834. require.Equal(t, 400, err.HTTPCode)
  835. require.Equal(t, 40015, err.Code)
  836. }
  837. func TestServer_PublishAttachmentTooLargeBodyVisitorAttachmentTotalSizeLimit(t *testing.T) {
  838. c := newTestConfig(t)
  839. c.VisitorAttachmentTotalSizeLimit = 10000
  840. s := newTestServer(t, c)
  841. response := request(t, s, "PUT", "/mytopic", util.RandomString(5000), nil)
  842. msg := toMessage(t, response.Body.String())
  843. require.Equal(t, 200, response.Code)
  844. require.Equal(t, "You received a file: attachment.txt", msg.Message)
  845. require.Equal(t, int64(5000), msg.Attachment.Size)
  846. content := util.RandomString(5001) // 5000+5001 > , see below
  847. response = request(t, s, "PUT", "/mytopic", content, nil)
  848. err := toHTTPError(t, response.Body.String())
  849. require.Equal(t, 400, response.Code)
  850. require.Equal(t, 400, err.HTTPCode)
  851. require.Equal(t, 40012, err.Code)
  852. }
  853. func TestServer_PublishAttachmentAndPrune(t *testing.T) {
  854. content := util.RandomString(5000) // > 4096
  855. c := newTestConfig(t)
  856. c.AttachmentExpiryDuration = time.Millisecond // Hack
  857. s := newTestServer(t, c)
  858. // Publish and make sure we can retrieve it
  859. response := request(t, s, "PUT", "/mytopic", content, nil)
  860. msg := toMessage(t, response.Body.String())
  861. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  862. file := filepath.Join(s.config.AttachmentCacheDir, msg.ID)
  863. require.FileExists(t, file)
  864. path := strings.TrimPrefix(msg.Attachment.URL, "http://127.0.0.1:12345")
  865. response = request(t, s, "GET", path, "", nil)
  866. require.Equal(t, 200, response.Code)
  867. require.Equal(t, content, response.Body.String())
  868. // Prune and makes sure it's gone
  869. time.Sleep(time.Second) // Sigh ...
  870. s.updateStatsAndPrune()
  871. require.NoFileExists(t, file)
  872. response = request(t, s, "GET", path, "", nil)
  873. require.Equal(t, 404, response.Code)
  874. }
  875. func TestServer_PublishAttachmentBandwidthLimit(t *testing.T) {
  876. content := util.RandomString(5000) // > 4096
  877. c := newTestConfig(t)
  878. c.VisitorAttachmentDailyBandwidthLimit = 5*5000 + 123 // A little more than 1 upload and 3 downloads
  879. s := newTestServer(t, c)
  880. // Publish attachment
  881. response := request(t, s, "PUT", "/mytopic", content, nil)
  882. msg := toMessage(t, response.Body.String())
  883. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  884. // Get it 4 times successfully
  885. path := strings.TrimPrefix(msg.Attachment.URL, "http://127.0.0.1:12345")
  886. for i := 1; i <= 4; i++ { // 4 successful downloads
  887. response = request(t, s, "GET", path, "", nil)
  888. require.Equal(t, 200, response.Code)
  889. require.Equal(t, content, response.Body.String())
  890. }
  891. // And then fail with a 429
  892. response = request(t, s, "GET", path, "", nil)
  893. err := toHTTPError(t, response.Body.String())
  894. require.Equal(t, 429, response.Code)
  895. require.Equal(t, 42905, err.Code)
  896. }
  897. func TestServer_PublishAttachmentBandwidthLimitUploadOnly(t *testing.T) {
  898. content := util.RandomString(5000) // > 4096
  899. c := newTestConfig(t)
  900. c.VisitorAttachmentDailyBandwidthLimit = 5*5000 + 500 // 5 successful uploads
  901. s := newTestServer(t, c)
  902. // 5 successful uploads
  903. for i := 1; i <= 5; i++ {
  904. response := request(t, s, "PUT", "/mytopic", content, nil)
  905. msg := toMessage(t, response.Body.String())
  906. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  907. }
  908. // And a failed one
  909. response := request(t, s, "PUT", "/mytopic", content, nil)
  910. err := toHTTPError(t, response.Body.String())
  911. require.Equal(t, 400, response.Code)
  912. require.Equal(t, 40012, err.Code)
  913. }
  914. func newTestConfig(t *testing.T) *Config {
  915. conf := NewConfig()
  916. conf.BaseURL = "http://127.0.0.1:12345"
  917. conf.CacheFile = filepath.Join(t.TempDir(), "cache.db")
  918. conf.AttachmentCacheDir = t.TempDir()
  919. return conf
  920. }
  921. func newTestServer(t *testing.T, config *Config) *Server {
  922. server, err := New(config)
  923. if err != nil {
  924. t.Fatal(err)
  925. }
  926. return server
  927. }
  928. func request(t *testing.T, s *Server, method, url, body string, headers map[string]string) *httptest.ResponseRecorder {
  929. rr := httptest.NewRecorder()
  930. req, err := http.NewRequest(method, url, strings.NewReader(body))
  931. if err != nil {
  932. t.Fatal(err)
  933. }
  934. req.RemoteAddr = "9.9.9.9" // Used for tests
  935. for k, v := range headers {
  936. req.Header.Set(k, v)
  937. }
  938. s.handle(rr, req)
  939. return rr
  940. }
  941. func subscribe(t *testing.T, s *Server, url string, rr *httptest.ResponseRecorder) context.CancelFunc {
  942. ctx, cancel := context.WithCancel(context.Background())
  943. req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
  944. if err != nil {
  945. t.Fatal(err)
  946. }
  947. done := make(chan bool)
  948. go func() {
  949. s.handle(rr, req)
  950. done <- true
  951. }()
  952. cancelAndWaitForDone := func() {
  953. time.Sleep(100 * time.Millisecond)
  954. cancel()
  955. <-done
  956. }
  957. time.Sleep(100 * time.Millisecond)
  958. return cancelAndWaitForDone
  959. }
  960. func toMessages(t *testing.T, s string) []*message {
  961. messages := make([]*message, 0)
  962. scanner := bufio.NewScanner(strings.NewReader(s))
  963. for scanner.Scan() {
  964. messages = append(messages, toMessage(t, scanner.Text()))
  965. }
  966. return messages
  967. }
  968. func toMessage(t *testing.T, s string) *message {
  969. var m message
  970. require.Nil(t, json.NewDecoder(strings.NewReader(s)).Decode(&m))
  971. return &m
  972. }
  973. func toHTTPError(t *testing.T, s string) *errHTTP {
  974. var e errHTTP
  975. require.Nil(t, json.NewDecoder(strings.NewReader(s)).Decode(&e))
  976. return &e
  977. }
  978. func firebaseServiceAccountFile(t *testing.T) string {
  979. if os.Getenv("NTFY_TEST_FIREBASE_SERVICE_ACCOUNT_FILE") != "" {
  980. return os.Getenv("NTFY_TEST_FIREBASE_SERVICE_ACCOUNT_FILE")
  981. } else if os.Getenv("NTFY_TEST_FIREBASE_SERVICE_ACCOUNT") != "" {
  982. filename := filepath.Join(t.TempDir(), "firebase.json")
  983. require.NotNil(t, os.WriteFile(filename, []byte(os.Getenv("NTFY_TEST_FIREBASE_SERVICE_ACCOUNT")), 0600))
  984. return filename
  985. }
  986. t.SkipNow()
  987. return ""
  988. }
  989. func basicAuth(s string) string {
  990. return fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(s)))
  991. }