server_test.go 46 KB

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