server_test.go 45 KB

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