server_test.go 58 KB

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