server_test.go 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461
  1. package server
  2. import (
  3. "bufio"
  4. "context"
  5. "encoding/base64"
  6. "encoding/json"
  7. "fmt"
  8. "golang.org/x/crypto/bcrypt"
  9. "heckel.io/ntfy/user"
  10. "io"
  11. "math/rand"
  12. "net/http"
  13. "net/http/httptest"
  14. "net/netip"
  15. "os"
  16. "path/filepath"
  17. "runtime/debug"
  18. "strings"
  19. "sync"
  20. "testing"
  21. "time"
  22. "github.com/stretchr/testify/assert"
  23. "github.com/stretchr/testify/require"
  24. "heckel.io/ntfy/log"
  25. "heckel.io/ntfy/util"
  26. )
  27. func TestMain(m *testing.M) {
  28. log.SetLevel(log.ErrorLevel)
  29. os.Exit(m.Run())
  30. }
  31. func TestServer_PublishAndPoll(t *testing.T) {
  32. s := newTestServer(t, newTestConfig(t))
  33. response1 := request(t, s, "PUT", "/mytopic", "my first message", nil)
  34. msg1 := toMessage(t, response1.Body.String())
  35. require.NotEmpty(t, msg1.ID)
  36. require.Equal(t, "my first message", msg1.Message)
  37. response2 := request(t, s, "PUT", "/mytopic", "my second\n\nmessage", nil)
  38. msg2 := toMessage(t, response2.Body.String())
  39. require.NotEqual(t, msg1.ID, msg2.ID)
  40. require.NotEmpty(t, msg2.ID)
  41. require.Equal(t, "my second\n\nmessage", msg2.Message)
  42. response := request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  43. messages := toMessages(t, response.Body.String())
  44. require.Equal(t, 2, len(messages))
  45. require.Equal(t, "my first message", messages[0].Message)
  46. require.Equal(t, "my second\n\nmessage", messages[1].Message)
  47. response = request(t, s, "GET", "/mytopic/sse?poll=1&since=all", "", nil)
  48. lines := strings.Split(strings.TrimSpace(response.Body.String()), "\n")
  49. require.Equal(t, 3, len(lines))
  50. require.Equal(t, "my first message", toMessage(t, strings.TrimPrefix(lines[0], "data: ")).Message)
  51. require.Equal(t, "", lines[1])
  52. require.Equal(t, "my second\n\nmessage", toMessage(t, strings.TrimPrefix(lines[2], "data: ")).Message)
  53. response = request(t, s, "GET", "/mytopic/raw?poll=1", "", nil)
  54. lines = strings.Split(strings.TrimSpace(response.Body.String()), "\n")
  55. require.Equal(t, 2, len(lines))
  56. require.Equal(t, "my first message", lines[0])
  57. require.Equal(t, "my second message", lines[1]) // \n -> " "
  58. }
  59. func TestServer_PublishWithFirebase(t *testing.T) {
  60. sender := newTestFirebaseSender(10)
  61. s := newTestServer(t, newTestConfig(t))
  62. s.firebaseClient = newFirebaseClient(sender, &testAuther{Allow: true})
  63. response := request(t, s, "PUT", "/mytopic", "my first message", nil)
  64. msg1 := toMessage(t, response.Body.String())
  65. require.NotEmpty(t, msg1.ID)
  66. require.Equal(t, "my first message", msg1.Message)
  67. time.Sleep(100 * time.Millisecond) // Firebase publishing happens
  68. require.Equal(t, 1, len(sender.Messages()))
  69. require.Equal(t, "my first message", sender.Messages()[0].Data["message"])
  70. require.Equal(t, "my first message", sender.Messages()[0].APNS.Payload.Aps.Alert.Body)
  71. require.Equal(t, "my first message", sender.Messages()[0].APNS.Payload.CustomData["message"])
  72. }
  73. func TestServer_PublishWithFirebase_WithoutUsers_AndWithoutPanic(t *testing.T) {
  74. // This tests issue #641, which used to panic before the fix
  75. firebaseKeyFile := filepath.Join(t.TempDir(), "firebase.json")
  76. contents := `{
  77. "type": "service_account",
  78. "project_id": "ntfy-test",
  79. "private_key_id": "fsfhskjdfhskdhfskdjfhsdf",
  80. "private_key": "lalala",
  81. "client_email": "firebase-adminsdk-muv04@ntfy-test.iam.gserviceaccount.com",
  82. "client_id": "123123213",
  83. "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  84. "token_uri": "https://oauth2.googleapis.com/token",
  85. "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  86. "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-muv04%40ntfy-test.iam.gserviceaccount.com"
  87. }
  88. `
  89. require.Nil(t, os.WriteFile(firebaseKeyFile, []byte(contents), 0600))
  90. c := newTestConfig(t)
  91. c.FirebaseKeyFile = firebaseKeyFile
  92. s := newTestServer(t, c)
  93. response := request(t, s, "PUT", "/mytopic", "my first message", nil)
  94. require.Equal(t, "my first message", toMessage(t, response.Body.String()).Message)
  95. }
  96. func TestServer_SubscribeOpenAndKeepalive(t *testing.T) {
  97. t.Parallel()
  98. c := newTestConfig(t)
  99. c.KeepaliveInterval = time.Second
  100. s := newTestServer(t, c)
  101. rr := httptest.NewRecorder()
  102. ctx, cancel := context.WithCancel(context.Background())
  103. req, err := http.NewRequestWithContext(ctx, "GET", "/mytopic/json", nil)
  104. if err != nil {
  105. t.Fatal(err)
  106. }
  107. doneChan := make(chan bool)
  108. go func() {
  109. s.handle(rr, req)
  110. doneChan <- true
  111. }()
  112. time.Sleep(1300 * time.Millisecond)
  113. cancel()
  114. <-doneChan
  115. messages := toMessages(t, rr.Body.String())
  116. require.Equal(t, 2, len(messages))
  117. require.Equal(t, openEvent, messages[0].Event)
  118. require.Equal(t, "mytopic", messages[0].Topic)
  119. require.Equal(t, "", messages[0].Message)
  120. require.Equal(t, "", messages[0].Title)
  121. require.Equal(t, 0, messages[0].Priority)
  122. require.Nil(t, messages[0].Tags)
  123. require.Equal(t, keepaliveEvent, messages[1].Event)
  124. require.Equal(t, "mytopic", messages[1].Topic)
  125. require.Equal(t, "", messages[1].Message)
  126. require.Equal(t, "", messages[1].Title)
  127. require.Equal(t, 0, messages[1].Priority)
  128. require.Nil(t, messages[1].Tags)
  129. }
  130. func TestServer_PublishAndSubscribe(t *testing.T) {
  131. t.Parallel()
  132. s := newTestServer(t, newTestConfig(t))
  133. subscribeRR := httptest.NewRecorder()
  134. subscribeCancel := subscribe(t, s, "/mytopic/json", subscribeRR)
  135. publishFirstRR := request(t, s, "PUT", "/mytopic", "my first message", nil)
  136. require.Equal(t, 200, publishFirstRR.Code)
  137. time.Sleep(500 * time.Millisecond) // Publishing is done asynchronously, this avoids races
  138. publishSecondRR := request(t, s, "PUT", "/mytopic", "my other message", map[string]string{
  139. "Title": " This is a title ",
  140. "X-Tags": "tag1,tag 2, tag3",
  141. "p": "1",
  142. })
  143. require.Equal(t, 200, publishSecondRR.Code)
  144. subscribeCancel()
  145. messages := toMessages(t, subscribeRR.Body.String())
  146. require.Equal(t, 3, len(messages))
  147. require.Equal(t, openEvent, messages[0].Event)
  148. require.Equal(t, messageEvent, messages[1].Event)
  149. require.Equal(t, "mytopic", messages[1].Topic)
  150. require.Equal(t, "my first message", messages[1].Message)
  151. require.Equal(t, "", messages[1].Title)
  152. require.Equal(t, 0, messages[1].Priority)
  153. require.Nil(t, messages[1].Tags)
  154. require.True(t, time.Now().Add(12*time.Hour-5*time.Second).Unix() < messages[1].Expires)
  155. require.True(t, time.Now().Add(12*time.Hour+5*time.Second).Unix() > messages[1].Expires)
  156. require.Equal(t, messageEvent, messages[2].Event)
  157. require.Equal(t, "mytopic", messages[2].Topic)
  158. require.Equal(t, "my other message", messages[2].Message)
  159. require.Equal(t, "This is a title", messages[2].Title)
  160. require.Equal(t, 1, messages[2].Priority)
  161. require.Equal(t, []string{"tag1", "tag 2", "tag3"}, messages[2].Tags)
  162. }
  163. func TestServer_Publish_Disallowed_Topic(t *testing.T) {
  164. c := newTestConfig(t)
  165. c.DisallowedTopics = []string{"about", "time", "this", "got", "added"}
  166. s := newTestServer(t, c)
  167. rr := request(t, s, "PUT", "/mytopic", "my first message", nil)
  168. require.Equal(t, 200, rr.Code)
  169. rr = request(t, s, "PUT", "/about", "another message", nil)
  170. require.Equal(t, 400, rr.Code)
  171. require.Equal(t, 40010, toHTTPError(t, rr.Body.String()).Code)
  172. }
  173. func TestServer_StaticSites(t *testing.T) {
  174. s := newTestServer(t, newTestConfig(t))
  175. rr := request(t, s, "GET", "/", "", nil)
  176. require.Equal(t, 200, rr.Code)
  177. require.Contains(t, rr.Body.String(), "</html>")
  178. rr = request(t, s, "HEAD", "/", "", nil)
  179. require.Equal(t, 200, rr.Code)
  180. rr = request(t, s, "OPTIONS", "/", "", nil)
  181. require.Equal(t, 200, rr.Code)
  182. rr = request(t, s, "GET", "/does-not-exist.txt", "", nil)
  183. require.Equal(t, 404, rr.Code)
  184. rr = request(t, s, "GET", "/mytopic", "", nil)
  185. require.Equal(t, 200, rr.Code)
  186. require.Contains(t, rr.Body.String(), `<meta name="robots" content="noindex, nofollow"/>`)
  187. rr = request(t, s, "GET", "/static/css/home.css", "", nil)
  188. require.Equal(t, 200, rr.Code)
  189. require.Contains(t, rr.Body.String(), `/* general styling */`)
  190. rr = request(t, s, "GET", "/docs", "", nil)
  191. require.Equal(t, 301, rr.Code)
  192. // Docs test removed, it was failing annoyingly.
  193. }
  194. func TestServer_WebEnabled(t *testing.T) {
  195. conf := newTestConfig(t)
  196. conf.EnableWeb = false
  197. s := newTestServer(t, conf)
  198. rr := request(t, s, "GET", "/", "", nil)
  199. require.Equal(t, 404, rr.Code)
  200. rr = request(t, s, "GET", "/config.js", "", nil)
  201. require.Equal(t, 404, rr.Code)
  202. rr = request(t, s, "GET", "/static/css/home.css", "", nil)
  203. require.Equal(t, 404, rr.Code)
  204. conf2 := newTestConfig(t)
  205. conf2.EnableWeb = true
  206. s2 := newTestServer(t, conf2)
  207. rr = request(t, s2, "GET", "/", "", nil)
  208. require.Equal(t, 200, rr.Code)
  209. rr = request(t, s2, "GET", "/config.js", "", nil)
  210. require.Equal(t, 200, rr.Code)
  211. rr = request(t, s2, "GET", "/static/css/home.css", "", nil)
  212. require.Equal(t, 200, rr.Code)
  213. }
  214. func TestServer_PublishLargeMessage(t *testing.T) {
  215. c := newTestConfig(t)
  216. c.AttachmentCacheDir = "" // Disable attachments
  217. s := newTestServer(t, c)
  218. body := strings.Repeat("this is a large message", 5000)
  219. response := request(t, s, "PUT", "/mytopic", body, nil)
  220. require.Equal(t, 400, response.Code)
  221. }
  222. func TestServer_PublishPriority(t *testing.T) {
  223. s := newTestServer(t, newTestConfig(t))
  224. for prio := 1; prio <= 5; prio++ {
  225. response := request(t, s, "GET", fmt.Sprintf("/mytopic/publish?priority=%d", prio), fmt.Sprintf("priority %d", prio), nil)
  226. msg := toMessage(t, response.Body.String())
  227. require.Equal(t, prio, msg.Priority)
  228. }
  229. response := request(t, s, "GET", "/mytopic/publish?priority=min", "test", nil)
  230. require.Equal(t, 1, toMessage(t, response.Body.String()).Priority)
  231. response = request(t, s, "GET", "/mytopic/send?priority=low", "test", nil)
  232. require.Equal(t, 2, toMessage(t, response.Body.String()).Priority)
  233. response = request(t, s, "GET", "/mytopic/send?priority=default", "test", nil)
  234. require.Equal(t, 3, toMessage(t, response.Body.String()).Priority)
  235. response = request(t, s, "GET", "/mytopic/send?priority=high", "test", nil)
  236. require.Equal(t, 4, toMessage(t, response.Body.String()).Priority)
  237. response = request(t, s, "GET", "/mytopic/send?priority=max", "test", nil)
  238. require.Equal(t, 5, toMessage(t, response.Body.String()).Priority)
  239. response = request(t, s, "GET", "/mytopic/trigger?priority=urgent", "test", nil)
  240. require.Equal(t, 5, toMessage(t, response.Body.String()).Priority)
  241. response = request(t, s, "GET", "/mytopic/trigger?priority=INVALID", "test", nil)
  242. require.Equal(t, 40007, toHTTPError(t, response.Body.String()).Code)
  243. }
  244. func TestServer_PublishGETOnlyOneTopic(t *testing.T) {
  245. // This tests a bug that allowed publishing topics with a comma in the name (no ticket)
  246. s := newTestServer(t, newTestConfig(t))
  247. response := request(t, s, "GET", "/mytopic,mytopic2/publish?m=hi", "", nil)
  248. require.Equal(t, 404, response.Code)
  249. }
  250. func TestServer_PublishNoCache(t *testing.T) {
  251. s := newTestServer(t, newTestConfig(t))
  252. response := request(t, s, "PUT", "/mytopic", "this message is not cached", map[string]string{
  253. "Cache": "no",
  254. })
  255. msg := toMessage(t, response.Body.String())
  256. require.NotEmpty(t, msg.ID)
  257. require.Equal(t, "this message is not cached", msg.Message)
  258. require.Equal(t, int64(0), msg.Expires)
  259. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  260. messages := toMessages(t, response.Body.String())
  261. require.Empty(t, messages)
  262. }
  263. func TestServer_PublishAt(t *testing.T) {
  264. t.Parallel()
  265. c := newTestConfig(t)
  266. c.MinDelay = time.Second
  267. c.DelayedSenderInterval = 100 * time.Millisecond
  268. s := newTestServer(t, c)
  269. response := request(t, s, "PUT", "/mytopic", "a message", map[string]string{
  270. "In": "1s",
  271. })
  272. require.Equal(t, 200, response.Code)
  273. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  274. messages := toMessages(t, response.Body.String())
  275. require.Equal(t, 0, len(messages))
  276. time.Sleep(time.Second)
  277. require.Nil(t, s.sendDelayedMessages())
  278. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  279. messages = toMessages(t, response.Body.String())
  280. require.Equal(t, 1, len(messages))
  281. require.Equal(t, "a message", messages[0].Message)
  282. require.Equal(t, netip.Addr{}, messages[0].Sender) // Never return the sender!
  283. messages, err := s.messageCache.Messages("mytopic", sinceAllMessages, true)
  284. require.Nil(t, err)
  285. require.Equal(t, 1, len(messages))
  286. require.Equal(t, "a message", messages[0].Message)
  287. require.Equal(t, "9.9.9.9", messages[0].Sender.String()) // It's stored in the DB though!
  288. }
  289. func TestServer_PublishAt_Expires(t *testing.T) {
  290. s := newTestServer(t, newTestConfig(t))
  291. response := request(t, s, "PUT", "/mytopic", "a message", map[string]string{
  292. "In": "2 days",
  293. })
  294. require.Equal(t, 200, response.Code)
  295. m := toMessage(t, response.Body.String())
  296. require.True(t, m.Expires > time.Now().Add(12*time.Hour+48*time.Hour-time.Minute).Unix())
  297. require.True(t, m.Expires < time.Now().Add(12*time.Hour+48*time.Hour+time.Minute).Unix())
  298. }
  299. func TestServer_PublishAtWithCacheError(t *testing.T) {
  300. s := newTestServer(t, newTestConfig(t))
  301. response := request(t, s, "PUT", "/mytopic", "a message", map[string]string{
  302. "Cache": "no",
  303. "In": "30 min",
  304. })
  305. require.Equal(t, 400, response.Code)
  306. require.Equal(t, errHTTPBadRequestDelayNoCache, toHTTPError(t, response.Body.String()))
  307. }
  308. func TestServer_PublishAtTooShortDelay(t *testing.T) {
  309. s := newTestServer(t, newTestConfig(t))
  310. response := request(t, s, "PUT", "/mytopic", "a message", map[string]string{
  311. "In": "1s",
  312. })
  313. require.Equal(t, 400, response.Code)
  314. }
  315. func TestServer_PublishAtTooLongDelay(t *testing.T) {
  316. s := newTestServer(t, newTestConfig(t))
  317. response := request(t, s, "PUT", "/mytopic", "a message", map[string]string{
  318. "In": "99999999h",
  319. })
  320. require.Equal(t, 400, response.Code)
  321. }
  322. func TestServer_PublishAtInvalidDelay(t *testing.T) {
  323. s := newTestServer(t, newTestConfig(t))
  324. response := request(t, s, "PUT", "/mytopic?delay=INVALID", "a message", nil)
  325. err := toHTTPError(t, response.Body.String())
  326. require.Equal(t, 400, response.Code)
  327. require.Equal(t, 40004, err.Code)
  328. }
  329. func TestServer_PublishAtTooLarge(t *testing.T) {
  330. s := newTestServer(t, newTestConfig(t))
  331. response := request(t, s, "PUT", "/mytopic?x-in=99999h", "a message", nil)
  332. err := toHTTPError(t, response.Body.String())
  333. require.Equal(t, 400, response.Code)
  334. require.Equal(t, 40006, err.Code)
  335. }
  336. func TestServer_PublishAtAndPrune(t *testing.T) {
  337. s := newTestServer(t, newTestConfig(t))
  338. response := request(t, s, "PUT", "/mytopic", "a message", map[string]string{
  339. "In": "1h",
  340. })
  341. require.Equal(t, 200, response.Code)
  342. s.execManager() // Fire pruning
  343. response = request(t, s, "GET", "/mytopic/json?poll=1&scheduled=1", "", nil)
  344. messages := toMessages(t, response.Body.String())
  345. require.Equal(t, 1, len(messages)) // Not affected by pruning
  346. require.Equal(t, "a message", messages[0].Message)
  347. }
  348. func TestServer_PublishAndMultiPoll(t *testing.T) {
  349. s := newTestServer(t, newTestConfig(t))
  350. response := request(t, s, "PUT", "/mytopic1", "message 1", nil)
  351. msg := toMessage(t, response.Body.String())
  352. require.NotEmpty(t, msg.ID)
  353. require.Equal(t, "mytopic1", msg.Topic)
  354. require.Equal(t, "message 1", msg.Message)
  355. response = request(t, s, "PUT", "/mytopic2", "message 2", nil)
  356. msg = toMessage(t, response.Body.String())
  357. require.NotEmpty(t, msg.ID)
  358. require.Equal(t, "mytopic2", msg.Topic)
  359. require.Equal(t, "message 2", msg.Message)
  360. response = request(t, s, "GET", "/mytopic1/json?poll=1", "", nil)
  361. messages := toMessages(t, response.Body.String())
  362. require.Equal(t, 1, len(messages))
  363. require.Equal(t, "mytopic1", messages[0].Topic)
  364. require.Equal(t, "message 1", messages[0].Message)
  365. response = request(t, s, "GET", "/mytopic1,mytopic2/json?poll=1", "", nil)
  366. messages = toMessages(t, response.Body.String())
  367. require.Equal(t, 2, len(messages))
  368. require.Equal(t, "mytopic1", messages[0].Topic)
  369. require.Equal(t, "message 1", messages[0].Message)
  370. require.Equal(t, "mytopic2", messages[1].Topic)
  371. require.Equal(t, "message 2", messages[1].Message)
  372. }
  373. func TestServer_PublishWithNopCache(t *testing.T) {
  374. c := newTestConfig(t)
  375. c.CacheDuration = 0
  376. s := newTestServer(t, c)
  377. subscribeRR := httptest.NewRecorder()
  378. subscribeCancel := subscribe(t, s, "/mytopic/json", subscribeRR)
  379. publishRR := request(t, s, "PUT", "/mytopic", "my first message", nil)
  380. require.Equal(t, 200, publishRR.Code)
  381. subscribeCancel()
  382. messages := toMessages(t, subscribeRR.Body.String())
  383. require.Equal(t, 2, len(messages))
  384. require.Equal(t, openEvent, messages[0].Event)
  385. require.Equal(t, messageEvent, messages[1].Event)
  386. require.Equal(t, "my first message", messages[1].Message)
  387. response := request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  388. messages = toMessages(t, response.Body.String())
  389. require.Empty(t, messages)
  390. }
  391. func TestServer_PublishAndPollSince(t *testing.T) {
  392. t.Parallel()
  393. s := newTestServer(t, newTestConfig(t))
  394. request(t, s, "PUT", "/mytopic", "test 1", nil)
  395. time.Sleep(1100 * time.Millisecond)
  396. since := time.Now().Unix()
  397. request(t, s, "PUT", "/mytopic", "test 2", nil)
  398. response := request(t, s, "GET", fmt.Sprintf("/mytopic/json?poll=1&since=%d", since), "", nil)
  399. messages := toMessages(t, response.Body.String())
  400. require.Equal(t, 1, len(messages))
  401. require.Equal(t, "test 2", messages[0].Message)
  402. response = request(t, s, "GET", "/mytopic/json?poll=1&since=10s", "", nil)
  403. messages = toMessages(t, response.Body.String())
  404. require.Equal(t, 2, len(messages))
  405. require.Equal(t, "test 1", messages[0].Message)
  406. response = request(t, s, "GET", "/mytopic/json?poll=1&since=100ms", "", nil)
  407. messages = toMessages(t, response.Body.String())
  408. require.Equal(t, 1, len(messages))
  409. require.Equal(t, "test 2", messages[0].Message)
  410. response = request(t, s, "GET", "/mytopic/json?poll=1&since=INVALID", "", nil)
  411. require.Equal(t, 40008, toHTTPError(t, response.Body.String()).Code)
  412. }
  413. func newMessageWithTimestamp(topic, message string, timestamp int64) *message {
  414. m := newDefaultMessage(topic, message)
  415. m.Time = timestamp
  416. return m
  417. }
  418. func TestServer_PollSinceID_MultipleTopics(t *testing.T) {
  419. s := newTestServer(t, newTestConfig(t))
  420. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic1", "test 1", 1655740277)))
  421. markerMessage := newMessageWithTimestamp("mytopic2", "test 2", 1655740283)
  422. require.Nil(t, s.messageCache.AddMessage(markerMessage))
  423. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic1", "test 3", 1655740289)))
  424. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic2", "test 4", 1655740293)))
  425. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic1", "test 5", 1655740297)))
  426. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic2", "test 6", 1655740303)))
  427. response := request(t, s, "GET", fmt.Sprintf("/mytopic1,mytopic2/json?poll=1&since=%s", markerMessage.ID), "", nil)
  428. messages := toMessages(t, response.Body.String())
  429. require.Equal(t, 4, len(messages))
  430. require.Equal(t, "test 3", messages[0].Message)
  431. require.Equal(t, "mytopic1", messages[0].Topic)
  432. require.Equal(t, "test 4", messages[1].Message)
  433. require.Equal(t, "mytopic2", messages[1].Topic)
  434. require.Equal(t, "test 5", messages[2].Message)
  435. require.Equal(t, "mytopic1", messages[2].Topic)
  436. require.Equal(t, "test 6", messages[3].Message)
  437. require.Equal(t, "mytopic2", messages[3].Topic)
  438. }
  439. func TestServer_PollSinceID_MultipleTopics_IDDoesNotMatch(t *testing.T) {
  440. s := newTestServer(t, newTestConfig(t))
  441. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic1", "test 3", 1655740289)))
  442. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic2", "test 4", 1655740293)))
  443. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic1", "test 5", 1655740297)))
  444. require.Nil(t, s.messageCache.AddMessage(newMessageWithTimestamp("mytopic2", "test 6", 1655740303)))
  445. response := request(t, s, "GET", "/mytopic1,mytopic2/json?poll=1&since=NoMatchForID", "", nil)
  446. messages := toMessages(t, response.Body.String())
  447. require.Equal(t, 4, len(messages))
  448. require.Equal(t, "test 3", messages[0].Message)
  449. require.Equal(t, "test 4", messages[1].Message)
  450. require.Equal(t, "test 5", messages[2].Message)
  451. require.Equal(t, "test 6", messages[3].Message)
  452. }
  453. func TestServer_PublishViaGET(t *testing.T) {
  454. s := newTestServer(t, newTestConfig(t))
  455. response := request(t, s, "GET", "/mytopic/trigger", "", nil)
  456. msg := toMessage(t, response.Body.String())
  457. require.NotEmpty(t, msg.ID)
  458. require.Equal(t, "triggered", msg.Message)
  459. 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)
  460. msg = toMessage(t, response.Body.String())
  461. require.NotEmpty(t, msg.ID)
  462. require.Equal(t, "This is a test", msg.Message)
  463. require.Equal(t, "This is a title", msg.Title)
  464. require.Equal(t, []string{"skull"}, msg.Tags)
  465. require.Equal(t, 5, msg.Priority)
  466. require.Greater(t, msg.Time, time.Now().Add(23*time.Hour).Unix())
  467. }
  468. func TestServer_PublishMessageInHeaderWithNewlines(t *testing.T) {
  469. s := newTestServer(t, newTestConfig(t))
  470. response := request(t, s, "PUT", "/mytopic", "", map[string]string{
  471. "Message": "Line 1\\nLine 2",
  472. })
  473. msg := toMessage(t, response.Body.String())
  474. require.NotEmpty(t, msg.ID)
  475. require.Equal(t, "Line 1\nLine 2", msg.Message) // \\n -> \n !
  476. }
  477. func TestServer_PublishInvalidTopic(t *testing.T) {
  478. s := newTestServer(t, newTestConfig(t))
  479. s.smtpSender = &testMailer{}
  480. response := request(t, s, "PUT", "/docs", "fail", nil)
  481. require.Equal(t, 40010, toHTTPError(t, response.Body.String()).Code)
  482. }
  483. func TestServer_PollWithQueryFilters(t *testing.T) {
  484. s := newTestServer(t, newTestConfig(t))
  485. response := request(t, s, "PUT", "/mytopic?priority=1&tags=tag1,tag2", "my first message", nil)
  486. msg := toMessage(t, response.Body.String())
  487. require.NotEmpty(t, msg.ID)
  488. response = request(t, s, "PUT", "/mytopic?title=a+title", "my second message", map[string]string{
  489. "Tags": "tag2,tag3",
  490. })
  491. msg = toMessage(t, response.Body.String())
  492. require.NotEmpty(t, msg.ID)
  493. queriesThatShouldReturnMessageOne := []string{
  494. "/mytopic/json?poll=1&priority=1",
  495. "/mytopic/json?poll=1&priority=min",
  496. "/mytopic/json?poll=1&priority=min,low",
  497. "/mytopic/json?poll=1&priority=1,2",
  498. "/mytopic/json?poll=1&p=2,min",
  499. "/mytopic/json?poll=1&tags=tag1",
  500. "/mytopic/json?poll=1&tags=tag1,tag2",
  501. "/mytopic/json?poll=1&message=my+first+message",
  502. }
  503. for _, query := range queriesThatShouldReturnMessageOne {
  504. response = request(t, s, "GET", query, "", nil)
  505. messages := toMessages(t, response.Body.String())
  506. require.Equal(t, 1, len(messages), "Query failed: "+query)
  507. require.Equal(t, "my first message", messages[0].Message, "Query failed: "+query)
  508. }
  509. queriesThatShouldReturnMessageTwo := []string{
  510. "/mytopic/json?poll=1&x-priority=3", // !
  511. "/mytopic/json?poll=1&priority=3",
  512. "/mytopic/json?poll=1&priority=default",
  513. "/mytopic/json?poll=1&p=3",
  514. "/mytopic/json?poll=1&x-tags=tag2,tag3",
  515. "/mytopic/json?poll=1&tags=tag2,tag3",
  516. "/mytopic/json?poll=1&tag=tag2,tag3",
  517. "/mytopic/json?poll=1&ta=tag2,tag3",
  518. "/mytopic/json?poll=1&x-title=a+title",
  519. "/mytopic/json?poll=1&title=a+title",
  520. "/mytopic/json?poll=1&t=a+title",
  521. "/mytopic/json?poll=1&x-message=my+second+message",
  522. "/mytopic/json?poll=1&message=my+second+message",
  523. "/mytopic/json?poll=1&m=my+second+message",
  524. "/mytopic/json?x-poll=1&m=my+second+message",
  525. "/mytopic/json?po=1&m=my+second+message",
  526. }
  527. for _, query := range queriesThatShouldReturnMessageTwo {
  528. response = request(t, s, "GET", query, "", nil)
  529. messages := toMessages(t, response.Body.String())
  530. require.Equal(t, 1, len(messages), "Query failed: "+query)
  531. require.Equal(t, "my second message", messages[0].Message, "Query failed: "+query)
  532. }
  533. queriesThatShouldReturnNoMessages := []string{
  534. "/mytopic/json?poll=1&priority=4",
  535. "/mytopic/json?poll=1&tags=tag1,tag2,tag3",
  536. "/mytopic/json?poll=1&title=another+title",
  537. "/mytopic/json?poll=1&message=my+third+message",
  538. "/mytopic/json?poll=1&message=my+third+message",
  539. }
  540. for _, query := range queriesThatShouldReturnNoMessages {
  541. response = request(t, s, "GET", query, "", nil)
  542. messages := toMessages(t, response.Body.String())
  543. require.Equal(t, 0, len(messages), "Query failed: "+query)
  544. }
  545. }
  546. func TestServer_SubscribeWithQueryFilters(t *testing.T) {
  547. t.Parallel()
  548. c := newTestConfig(t)
  549. c.KeepaliveInterval = 800 * time.Millisecond
  550. s := newTestServer(t, c)
  551. subscribeResponse := httptest.NewRecorder()
  552. subscribeCancel := subscribe(t, s, "/mytopic/json?tags=zfs-issue", subscribeResponse)
  553. response := request(t, s, "PUT", "/mytopic", "my first message", nil)
  554. require.Equal(t, 200, response.Code)
  555. response = request(t, s, "PUT", "/mytopic", "ZFS scrub failed", map[string]string{
  556. "Tags": "zfs-issue,zfs-scrub",
  557. })
  558. require.Equal(t, 200, response.Code)
  559. time.Sleep(850 * time.Millisecond)
  560. subscribeCancel()
  561. messages := toMessages(t, subscribeResponse.Body.String())
  562. require.Equal(t, 3, len(messages))
  563. require.Equal(t, openEvent, messages[0].Event)
  564. require.Equal(t, messageEvent, messages[1].Event)
  565. require.Equal(t, "ZFS scrub failed", messages[1].Message)
  566. require.Equal(t, keepaliveEvent, messages[2].Event)
  567. }
  568. func TestServer_Auth_Success_Admin(t *testing.T) {
  569. c := newTestConfigWithAuthFile(t)
  570. s := newTestServer(t, c)
  571. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleAdmin))
  572. response := request(t, s, "GET", "/mytopic/auth", "", map[string]string{
  573. "Authorization": util.BasicAuth("phil", "phil"),
  574. })
  575. require.Equal(t, 200, response.Code)
  576. require.Equal(t, `{"success":true}`+"\n", response.Body.String())
  577. }
  578. func TestServer_Auth_Success_User(t *testing.T) {
  579. c := newTestConfigWithAuthFile(t)
  580. c.AuthDefault = user.PermissionDenyAll
  581. s := newTestServer(t, c)
  582. require.Nil(t, s.userManager.AddUser("ben", "ben", user.RoleUser))
  583. require.Nil(t, s.userManager.AllowAccess("ben", "mytopic", user.PermissionReadWrite))
  584. response := request(t, s, "GET", "/mytopic/auth", "", map[string]string{
  585. "Authorization": util.BasicAuth("ben", "ben"),
  586. })
  587. require.Equal(t, 200, response.Code)
  588. }
  589. func TestServer_Auth_Success_User_MultipleTopics(t *testing.T) {
  590. c := newTestConfigWithAuthFile(t)
  591. c.AuthDefault = user.PermissionDenyAll
  592. s := newTestServer(t, c)
  593. require.Nil(t, s.userManager.AddUser("ben", "ben", user.RoleUser))
  594. require.Nil(t, s.userManager.AllowAccess("ben", "mytopic", user.PermissionReadWrite))
  595. require.Nil(t, s.userManager.AllowAccess("ben", "anothertopic", user.PermissionReadWrite))
  596. response := request(t, s, "GET", "/mytopic,anothertopic/auth", "", map[string]string{
  597. "Authorization": util.BasicAuth("ben", "ben"),
  598. })
  599. require.Equal(t, 200, response.Code)
  600. response = request(t, s, "GET", "/mytopic,anothertopic,NOT-THIS-ONE/auth", "", map[string]string{
  601. "Authorization": util.BasicAuth("ben", "ben"),
  602. })
  603. require.Equal(t, 403, response.Code)
  604. }
  605. func TestServer_Auth_Fail_InvalidPass(t *testing.T) {
  606. c := newTestConfig(t)
  607. c.AuthFile = filepath.Join(t.TempDir(), "user.db")
  608. c.AuthDefault = user.PermissionDenyAll
  609. s := newTestServer(t, c)
  610. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleAdmin))
  611. response := request(t, s, "GET", "/mytopic/auth", "", map[string]string{
  612. "Authorization": util.BasicAuth("phil", "INVALID"),
  613. })
  614. require.Equal(t, 401, response.Code)
  615. }
  616. func TestServer_Auth_Fail_Unauthorized(t *testing.T) {
  617. c := newTestConfigWithAuthFile(t)
  618. c.AuthDefault = user.PermissionDenyAll
  619. s := newTestServer(t, c)
  620. require.Nil(t, s.userManager.AddUser("ben", "ben", user.RoleUser))
  621. require.Nil(t, s.userManager.AllowAccess("ben", "sometopic", user.PermissionReadWrite)) // Not mytopic!
  622. response := request(t, s, "GET", "/mytopic/auth", "", map[string]string{
  623. "Authorization": util.BasicAuth("ben", "ben"),
  624. })
  625. require.Equal(t, 403, response.Code)
  626. }
  627. func TestServer_Auth_Fail_CannotPublish(t *testing.T) {
  628. c := newTestConfigWithAuthFile(t)
  629. c.AuthDefault = user.PermissionReadWrite // Open by default
  630. s := newTestServer(t, c)
  631. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleAdmin))
  632. require.Nil(t, s.userManager.AllowAccess(user.Everyone, "private", user.PermissionDenyAll))
  633. require.Nil(t, s.userManager.AllowAccess(user.Everyone, "announcements", user.PermissionRead))
  634. response := request(t, s, "PUT", "/mytopic", "test", nil)
  635. require.Equal(t, 200, response.Code)
  636. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  637. require.Equal(t, 200, response.Code)
  638. response = request(t, s, "PUT", "/announcements", "test", nil)
  639. require.Equal(t, 403, response.Code) // Cannot write as anonymous
  640. response = request(t, s, "PUT", "/announcements", "test", map[string]string{
  641. "Authorization": util.BasicAuth("phil", "phil"),
  642. })
  643. require.Equal(t, 200, response.Code)
  644. response = request(t, s, "GET", "/announcements/json?poll=1", "", nil)
  645. require.Equal(t, 200, response.Code) // Anonymous read allowed
  646. response = request(t, s, "GET", "/private/json?poll=1", "", nil)
  647. require.Equal(t, 403, response.Code) // Anonymous read not allowed
  648. }
  649. func TestServer_Auth_Fail_Rate_Limiting(t *testing.T) {
  650. c := newTestConfigWithAuthFile(t)
  651. s := newTestServer(t, c)
  652. for i := 0; i < 10; i++ {
  653. response := request(t, s, "PUT", "/announcements", "test", map[string]string{
  654. "Authorization": util.BasicAuth("phil", "phil"),
  655. })
  656. require.Equal(t, 401, response.Code)
  657. }
  658. response := request(t, s, "PUT", "/announcements", "test", map[string]string{
  659. "Authorization": util.BasicAuth("phil", "phil"),
  660. })
  661. require.Equal(t, 429, response.Code)
  662. require.Equal(t, 42909, toHTTPError(t, response.Body.String()).Code)
  663. }
  664. func TestServer_Auth_ViaQuery(t *testing.T) {
  665. c := newTestConfigWithAuthFile(t)
  666. c.AuthDefault = user.PermissionDenyAll
  667. s := newTestServer(t, c)
  668. require.Nil(t, s.userManager.AddUser("ben", "some pass", user.RoleAdmin))
  669. u := fmt.Sprintf("/mytopic/json?poll=1&auth=%s", base64.RawURLEncoding.EncodeToString([]byte(util.BasicAuth("ben", "some pass"))))
  670. response := request(t, s, "GET", u, "", nil)
  671. require.Equal(t, 200, response.Code)
  672. u = fmt.Sprintf("/mytopic/json?poll=1&auth=%s", base64.RawURLEncoding.EncodeToString([]byte(util.BasicAuth("ben", "WRONNNGGGG"))))
  673. response = request(t, s, "GET", u, "", nil)
  674. require.Equal(t, 401, response.Code)
  675. }
  676. func TestServer_Auth_NonBasicHeader(t *testing.T) {
  677. s := newTestServer(t, newTestConfigWithAuthFile(t))
  678. response := request(t, s, "PUT", "/mytopic", "test", map[string]string{
  679. "Authorization": "WebPush not-supported",
  680. })
  681. require.Equal(t, 200, response.Code)
  682. response = request(t, s, "PUT", "/mytopic", "test", map[string]string{
  683. "Authorization": "Bearer supported",
  684. })
  685. require.Equal(t, 401, response.Code)
  686. response = request(t, s, "PUT", "/mytopic", "test", map[string]string{
  687. "Authorization": "basic supported",
  688. })
  689. require.Equal(t, 401, response.Code)
  690. }
  691. func TestServer_StatsResetter(t *testing.T) {
  692. t.Parallel()
  693. // This tests the stats resetter for
  694. // - an anonymous user
  695. // - a user without a tier (treated like the same as the anonymous user)
  696. // - a user with a tier
  697. c := newTestConfigWithAuthFile(t)
  698. c.VisitorStatsResetTime = time.Now().Add(2 * time.Second)
  699. s := newTestServer(t, c)
  700. go s.runStatsResetter()
  701. // Create user with tier (tieruser) and user without tier (phil)
  702. require.Nil(t, s.userManager.AddTier(&user.Tier{
  703. Code: "test",
  704. MessageLimit: 5,
  705. MessageExpiryDuration: -5 * time.Second, // Second, what a hack!
  706. }))
  707. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser))
  708. require.Nil(t, s.userManager.AddUser("tieruser", "tieruser", user.RoleUser))
  709. require.Nil(t, s.userManager.ChangeTier("tieruser", "test"))
  710. // Send an anonymous message
  711. response := request(t, s, "PUT", "/mytopic", "test", nil)
  712. require.Equal(t, 200, response.Code)
  713. // Send messages from user without tier (phil)
  714. for i := 0; i < 5; i++ {
  715. response := request(t, s, "PUT", "/mytopic", "test", map[string]string{
  716. "Authorization": util.BasicAuth("phil", "phil"),
  717. })
  718. require.Equal(t, 200, response.Code)
  719. }
  720. // Send messages from user with tier
  721. for i := 0; i < 2; i++ {
  722. response := request(t, s, "PUT", "/mytopic", "test", map[string]string{
  723. "Authorization": util.BasicAuth("tieruser", "tieruser"),
  724. })
  725. require.Equal(t, 200, response.Code)
  726. }
  727. // User stats show 6 messages (for user without tier)
  728. response = request(t, s, "GET", "/v1/account", "", map[string]string{
  729. "Authorization": util.BasicAuth("phil", "phil"),
  730. })
  731. require.Equal(t, 200, response.Code)
  732. account, err := util.UnmarshalJSON[apiAccountResponse](io.NopCloser(response.Body))
  733. require.Nil(t, err)
  734. require.Equal(t, int64(6), account.Stats.Messages)
  735. // User stats show 6 messages (for anonymous visitor)
  736. response = request(t, s, "GET", "/v1/account", "", nil)
  737. require.Equal(t, 200, response.Code)
  738. account, err = util.UnmarshalJSON[apiAccountResponse](io.NopCloser(response.Body))
  739. require.Nil(t, err)
  740. require.Equal(t, int64(6), account.Stats.Messages)
  741. // User stats show 2 messages (for user with tier)
  742. response = request(t, s, "GET", "/v1/account", "", map[string]string{
  743. "Authorization": util.BasicAuth("tieruser", "tieruser"),
  744. })
  745. require.Equal(t, 200, response.Code)
  746. account, err = util.UnmarshalJSON[apiAccountResponse](io.NopCloser(response.Body))
  747. require.Nil(t, err)
  748. require.Equal(t, int64(2), account.Stats.Messages)
  749. // Wait for stats resetter to run
  750. waitFor(t, func() bool {
  751. response = request(t, s, "GET", "/v1/account", "", map[string]string{
  752. "Authorization": util.BasicAuth("phil", "phil"),
  753. })
  754. require.Equal(t, 200, response.Code)
  755. account, err = util.UnmarshalJSON[apiAccountResponse](io.NopCloser(response.Body))
  756. require.Nil(t, err)
  757. return account.Stats.Messages == 0
  758. })
  759. // User stats show 0 messages now!
  760. response = request(t, s, "GET", "/v1/account", "", map[string]string{
  761. "Authorization": util.BasicAuth("phil", "phil"),
  762. })
  763. require.Equal(t, 200, response.Code)
  764. account, err = util.UnmarshalJSON[apiAccountResponse](io.NopCloser(response.Body))
  765. require.Nil(t, err)
  766. require.Equal(t, int64(0), account.Stats.Messages)
  767. // Since this is a user without a tier, the anonymous user should have the same stats
  768. response = request(t, s, "GET", "/v1/account", "", nil)
  769. require.Equal(t, 200, response.Code)
  770. account, err = util.UnmarshalJSON[apiAccountResponse](io.NopCloser(response.Body))
  771. require.Nil(t, err)
  772. require.Equal(t, int64(0), account.Stats.Messages)
  773. // User stats show 0 messages (for user with tier)
  774. response = request(t, s, "GET", "/v1/account", "", map[string]string{
  775. "Authorization": util.BasicAuth("tieruser", "tieruser"),
  776. })
  777. require.Equal(t, 200, response.Code)
  778. account, err = util.UnmarshalJSON[apiAccountResponse](io.NopCloser(response.Body))
  779. require.Nil(t, err)
  780. require.Equal(t, int64(0), account.Stats.Messages)
  781. }
  782. func TestServer_StatsResetter_MessageLimiter_EmailsLimiter(t *testing.T) {
  783. // This tests that the messageLimiter (the only fixed limiter) and the emailsLimiter (token bucket)
  784. // is reset by the stats resetter
  785. c := newTestConfigWithAuthFile(t)
  786. s := newTestServer(t, c)
  787. s.smtpSender = &testMailer{}
  788. // Publish some messages, and check stats
  789. for i := 0; i < 3; i++ {
  790. response := request(t, s, "PUT", "/mytopic", "test", nil)
  791. require.Equal(t, 200, response.Code)
  792. }
  793. response := request(t, s, "PUT", "/mytopic", "test", map[string]string{
  794. "Email": "test@email.com",
  795. })
  796. require.Equal(t, 200, response.Code)
  797. rr := request(t, s, "GET", "/v1/account", "", nil)
  798. require.Equal(t, 200, rr.Code)
  799. account, err := util.UnmarshalJSON[apiAccountResponse](io.NopCloser(rr.Body))
  800. require.Nil(t, err)
  801. require.Equal(t, int64(4), account.Stats.Messages)
  802. require.Equal(t, int64(1), account.Stats.Emails)
  803. v := s.visitor(netip.MustParseAddr("9.9.9.9"), nil)
  804. require.Equal(t, int64(4), v.Stats().Messages)
  805. require.Equal(t, int64(4), v.messagesLimiter.Value())
  806. require.Equal(t, int64(1), v.Stats().Emails)
  807. require.Equal(t, int64(1), v.emailsLimiter.Value())
  808. // Reset stats and check again
  809. s.resetStats()
  810. rr = request(t, s, "GET", "/v1/account", "", nil)
  811. require.Equal(t, 200, rr.Code)
  812. account, err = util.UnmarshalJSON[apiAccountResponse](io.NopCloser(rr.Body))
  813. require.Nil(t, err)
  814. require.Equal(t, int64(0), account.Stats.Messages)
  815. require.Equal(t, int64(0), account.Stats.Emails)
  816. v = s.visitor(netip.MustParseAddr("9.9.9.9"), nil)
  817. require.Equal(t, int64(0), v.Stats().Messages)
  818. require.Equal(t, int64(0), v.messagesLimiter.Value())
  819. require.Equal(t, int64(0), v.Stats().Emails)
  820. require.Equal(t, int64(0), v.emailsLimiter.Value())
  821. }
  822. func TestServer_DailyMessageQuotaFromDatabase(t *testing.T) {
  823. t.Parallel()
  824. // This tests that the daily message quota is prefilled originally from the database,
  825. // if the visitor is unknown
  826. c := newTestConfigWithAuthFile(t)
  827. c.AuthStatsQueueWriterInterval = 100 * time.Millisecond
  828. s := newTestServer(t, c)
  829. // Create user, and update it with some message and email stats
  830. require.Nil(t, s.userManager.AddTier(&user.Tier{
  831. Code: "test",
  832. }))
  833. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser))
  834. require.Nil(t, s.userManager.ChangeTier("phil", "test"))
  835. u, err := s.userManager.User("phil")
  836. require.Nil(t, err)
  837. s.userManager.EnqueueUserStats(u.ID, &user.Stats{
  838. Messages: 123456,
  839. Emails: 999,
  840. })
  841. time.Sleep(400 * time.Millisecond)
  842. // Get account and verify stats are read from the DB, and that the visitor also has these stats
  843. rr := request(t, s, "GET", "/v1/account", "", map[string]string{
  844. "Authorization": util.BasicAuth("phil", "phil"),
  845. })
  846. require.Equal(t, 200, rr.Code)
  847. account, err := util.UnmarshalJSON[apiAccountResponse](io.NopCloser(rr.Body))
  848. require.Nil(t, err)
  849. require.Equal(t, int64(123456), account.Stats.Messages)
  850. require.Equal(t, int64(999), account.Stats.Emails)
  851. v := s.visitor(netip.MustParseAddr("9.9.9.9"), u)
  852. require.Equal(t, int64(123456), v.Stats().Messages)
  853. require.Equal(t, int64(123456), v.messagesLimiter.Value())
  854. require.Equal(t, int64(999), v.Stats().Emails)
  855. require.Equal(t, int64(999), v.emailsLimiter.Value())
  856. }
  857. type testMailer struct {
  858. count int
  859. mu sync.Mutex
  860. }
  861. func (t *testMailer) Send(v *visitor, m *message, to string) error {
  862. t.mu.Lock()
  863. defer t.mu.Unlock()
  864. t.count++
  865. return nil
  866. }
  867. func (t *testMailer) Counts() (total int64, success int64, failure int64) {
  868. return 0, 0, 0
  869. }
  870. func (t *testMailer) Count() int {
  871. t.mu.Lock()
  872. defer t.mu.Unlock()
  873. return t.count
  874. }
  875. func TestServer_PublishTooRequests_Defaults(t *testing.T) {
  876. s := newTestServer(t, newTestConfig(t))
  877. for i := 0; i < 60; i++ {
  878. response := request(t, s, "PUT", "/mytopic", fmt.Sprintf("message %d", i), nil)
  879. require.Equal(t, 200, response.Code)
  880. }
  881. response := request(t, s, "PUT", "/mytopic", "message", nil)
  882. require.Equal(t, 429, response.Code)
  883. }
  884. func TestServer_PublishTooRequests_Defaults_ExemptHosts(t *testing.T) {
  885. c := newTestConfig(t)
  886. c.VisitorRequestLimitBurst = 3
  887. c.VisitorRequestExemptIPAddrs = []netip.Prefix{netip.MustParsePrefix("9.9.9.9/32")} // see request()
  888. s := newTestServer(t, c)
  889. for i := 0; i < 5; i++ { // > 3
  890. response := request(t, s, "PUT", "/mytopic", fmt.Sprintf("message %d", i), nil)
  891. require.Equal(t, 200, response.Code)
  892. }
  893. }
  894. func TestServer_PublishTooRequests_Defaults_ExemptHosts_MessageDailyLimit(t *testing.T) {
  895. c := newTestConfig(t)
  896. c.VisitorRequestLimitBurst = 10
  897. c.VisitorMessageDailyLimit = 4
  898. c.VisitorRequestExemptIPAddrs = []netip.Prefix{netip.MustParsePrefix("9.9.9.9/32")} // see request()
  899. s := newTestServer(t, c)
  900. for i := 0; i < 8; i++ { // 4
  901. response := request(t, s, "PUT", "/mytopic", "message", nil)
  902. require.Equal(t, 200, response.Code)
  903. }
  904. }
  905. func TestServer_PublishTooRequests_ShortReplenish(t *testing.T) {
  906. t.Parallel()
  907. c := newTestConfig(t)
  908. c.VisitorRequestLimitBurst = 60
  909. c.VisitorRequestLimitReplenish = time.Second
  910. s := newTestServer(t, c)
  911. for i := 0; i < 60; i++ {
  912. response := request(t, s, "PUT", "/mytopic", fmt.Sprintf("message %d", i), nil)
  913. require.Equal(t, 200, response.Code)
  914. }
  915. response := request(t, s, "PUT", "/mytopic", "message", nil)
  916. require.Equal(t, 429, response.Code)
  917. time.Sleep(1020 * time.Millisecond)
  918. response = request(t, s, "PUT", "/mytopic", "message", nil)
  919. require.Equal(t, 200, response.Code)
  920. }
  921. func TestServer_PublishTooManyEmails_Defaults(t *testing.T) {
  922. s := newTestServer(t, newTestConfig(t))
  923. s.smtpSender = &testMailer{}
  924. for i := 0; i < 16; i++ {
  925. response := request(t, s, "PUT", "/mytopic", fmt.Sprintf("message %d", i), map[string]string{
  926. "E-Mail": "test@example.com",
  927. })
  928. require.Equal(t, 200, response.Code)
  929. }
  930. response := request(t, s, "PUT", "/mytopic", "one too many", map[string]string{
  931. "E-Mail": "test@example.com",
  932. })
  933. require.Equal(t, 429, response.Code)
  934. }
  935. func TestServer_PublishTooManyEmails_Replenish(t *testing.T) {
  936. t.Parallel()
  937. c := newTestConfig(t)
  938. c.VisitorEmailLimitReplenish = 500 * time.Millisecond
  939. s := newTestServer(t, c)
  940. s.smtpSender = &testMailer{}
  941. for i := 0; i < 16; i++ {
  942. response := request(t, s, "PUT", "/mytopic", fmt.Sprintf("message %d", i), map[string]string{
  943. "E-Mail": "test@example.com",
  944. })
  945. require.Equal(t, 200, response.Code)
  946. }
  947. response := request(t, s, "PUT", "/mytopic", "one too many", map[string]string{
  948. "E-Mail": "test@example.com",
  949. })
  950. require.Equal(t, 429, response.Code)
  951. time.Sleep(510 * time.Millisecond)
  952. response = request(t, s, "PUT", "/mytopic", "this should be okay again too many", map[string]string{
  953. "E-Mail": "test@example.com",
  954. })
  955. require.Equal(t, 200, response.Code)
  956. response = request(t, s, "PUT", "/mytopic", "and bad again", map[string]string{
  957. "E-Mail": "test@example.com",
  958. })
  959. require.Equal(t, 429, response.Code)
  960. }
  961. func TestServer_PublishDelayedEmail_Fail(t *testing.T) {
  962. s := newTestServer(t, newTestConfig(t))
  963. s.smtpSender = &testMailer{}
  964. response := request(t, s, "PUT", "/mytopic", "fail", map[string]string{
  965. "E-Mail": "test@example.com",
  966. "Delay": "20 min",
  967. })
  968. require.Equal(t, 400, response.Code)
  969. }
  970. func TestServer_PublishEmailNoMailer_Fail(t *testing.T) {
  971. s := newTestServer(t, newTestConfig(t))
  972. response := request(t, s, "PUT", "/mytopic", "fail", map[string]string{
  973. "E-Mail": "test@example.com",
  974. })
  975. require.Equal(t, 400, response.Code)
  976. }
  977. func TestServer_PublishAndExpungeTopicAfter16Hours(t *testing.T) {
  978. t.Parallel()
  979. s := newTestServer(t, newTestConfig(t))
  980. subFn := func(v *visitor, msg *message) error {
  981. return nil
  982. }
  983. // Publish and check last access
  984. response := request(t, s, "POST", "/mytopic", "test", map[string]string{
  985. "Cache": "no",
  986. })
  987. require.Equal(t, 200, response.Code)
  988. require.True(t, s.topics["mytopic"].lastAccess.Unix() >= time.Now().Unix()-2)
  989. require.True(t, s.topics["mytopic"].lastAccess.Unix() <= time.Now().Unix()+2)
  990. // Topic won't get pruned
  991. s.execManager()
  992. require.NotNil(t, s.topics["mytopic"])
  993. // Fudge with last access, but subscribe, and see that it won't get pruned (because of subscriber)
  994. subID := s.topics["mytopic"].Subscribe(subFn, "", func() {})
  995. s.topics["mytopic"].lastAccess = time.Now().Add(-17 * time.Hour)
  996. s.execManager()
  997. require.NotNil(t, s.topics["mytopic"])
  998. // It'll finally get pruned now that there are no subscribers and last access is 17 hours ago
  999. s.topics["mytopic"].Unsubscribe(subID)
  1000. s.execManager()
  1001. require.Nil(t, s.topics["mytopic"])
  1002. }
  1003. func TestServer_TopicKeepaliveOnPoll(t *testing.T) {
  1004. t.Parallel()
  1005. s := newTestServer(t, newTestConfig(t))
  1006. // Create topic by polling once
  1007. response := request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  1008. require.Equal(t, 200, response.Code)
  1009. // Mess with last access time
  1010. s.topics["mytopic"].lastAccess = time.Now().Add(-17 * time.Hour)
  1011. // Poll again and check keepalive time
  1012. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  1013. require.Equal(t, 200, response.Code)
  1014. require.True(t, s.topics["mytopic"].lastAccess.Unix() >= time.Now().Unix()-2)
  1015. require.True(t, s.topics["mytopic"].lastAccess.Unix() <= time.Now().Unix()+2)
  1016. }
  1017. func TestServer_UnifiedPushDiscovery(t *testing.T) {
  1018. s := newTestServer(t, newTestConfig(t))
  1019. response := request(t, s, "GET", "/mytopic?up=1", "", nil)
  1020. require.Equal(t, 200, response.Code)
  1021. require.Equal(t, `{"unifiedpush":{"version":1}}`+"\n", response.Body.String())
  1022. }
  1023. func TestServer_PublishUnifiedPushBinary_AndPoll(t *testing.T) {
  1024. b := make([]byte, 12) // Max length
  1025. _, err := rand.Read(b)
  1026. require.Nil(t, err)
  1027. s := newTestServer(t, newTestConfig(t))
  1028. // Register a UnifiedPush subscriber
  1029. response := request(t, s, "GET", "/up123456789012/json?poll=1", "", map[string]string{
  1030. "Rate-Topics": "up123456789012",
  1031. })
  1032. require.Equal(t, 200, response.Code)
  1033. // Publish message to topic
  1034. response = request(t, s, "PUT", "/up123456789012?up=1", string(b), nil)
  1035. require.Equal(t, 200, response.Code)
  1036. m := toMessage(t, response.Body.String())
  1037. require.Equal(t, "base64", m.Encoding)
  1038. b2, err := base64.StdEncoding.DecodeString(m.Message)
  1039. require.Nil(t, err)
  1040. require.Equal(t, b, b2)
  1041. // Retrieve and check published message
  1042. response = request(t, s, "GET", "/up123456789012/json?poll=1", string(b), nil)
  1043. require.Equal(t, 200, response.Code)
  1044. m = toMessage(t, response.Body.String())
  1045. require.Equal(t, "base64", m.Encoding)
  1046. b2, err = base64.StdEncoding.DecodeString(m.Message)
  1047. require.Nil(t, err)
  1048. require.Equal(t, b, b2)
  1049. }
  1050. func TestServer_PublishUnifiedPushBinary_Truncated(t *testing.T) {
  1051. b := make([]byte, 5000) // Longer than max length
  1052. _, err := rand.Read(b)
  1053. require.Nil(t, err)
  1054. s := newTestServer(t, newTestConfig(t))
  1055. // Register a UnifiedPush subscriber
  1056. response := request(t, s, "GET", "/mytopic/json?poll=1", "", map[string]string{
  1057. "Rate-Topics": "mytopic",
  1058. })
  1059. require.Equal(t, 200, response.Code)
  1060. // Publish message to topic
  1061. response = request(t, s, "PUT", "/mytopic?up=1", string(b), nil)
  1062. require.Equal(t, 200, response.Code)
  1063. m := toMessage(t, response.Body.String())
  1064. require.Equal(t, "base64", m.Encoding)
  1065. b2, err := base64.StdEncoding.DecodeString(m.Message)
  1066. require.Nil(t, err)
  1067. require.Equal(t, 4096, len(b2))
  1068. require.Equal(t, b[:4096], b2)
  1069. }
  1070. func TestServer_PublishUnifiedPushText(t *testing.T) {
  1071. s := newTestServer(t, newTestConfig(t))
  1072. // Register a UnifiedPush subscriber
  1073. response := request(t, s, "GET", "/mytopic/json?poll=1", "", map[string]string{
  1074. "Rate-Topics": "mytopic",
  1075. })
  1076. require.Equal(t, 200, response.Code)
  1077. // Publish UnifiedPush text message
  1078. response = request(t, s, "PUT", "/mytopic?up=1", "this is a unifiedpush text message", nil)
  1079. require.Equal(t, 200, response.Code)
  1080. m := toMessage(t, response.Body.String())
  1081. require.Equal(t, "", m.Encoding)
  1082. require.Equal(t, "this is a unifiedpush text message", m.Message)
  1083. }
  1084. func TestServer_MatrixGateway_Discovery_Success(t *testing.T) {
  1085. s := newTestServer(t, newTestConfig(t))
  1086. response := request(t, s, "GET", "/_matrix/push/v1/notify", "", nil)
  1087. require.Equal(t, 200, response.Code)
  1088. require.Equal(t, `{"unifiedpush":{"gateway":"matrix"}}`+"\n", response.Body.String())
  1089. }
  1090. func TestServer_MatrixGateway_Discovery_Failure_Unconfigured(t *testing.T) {
  1091. c := newTestConfig(t)
  1092. c.BaseURL = ""
  1093. s := newTestServer(t, c)
  1094. response := request(t, s, "GET", "/_matrix/push/v1/notify", "", nil)
  1095. require.Equal(t, 500, response.Code)
  1096. err := toHTTPError(t, response.Body.String())
  1097. require.Equal(t, 50003, err.Code)
  1098. }
  1099. func TestServer_MatrixGateway_Push_Success(t *testing.T) {
  1100. s := newTestServer(t, newTestConfig(t))
  1101. response := request(t, s, "GET", "/mytopic/json?poll=1", "", map[string]string{
  1102. "Rate-Topics": "mytopic", // Register first!
  1103. })
  1104. require.Equal(t, 200, response.Code)
  1105. notification := `{"notification":{"devices":[{"pushkey":"http://127.0.0.1:12345/mytopic?up=1"}]}}`
  1106. response = request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1107. require.Equal(t, 200, response.Code)
  1108. require.Equal(t, `{"rejected":[]}`+"\n", response.Body.String())
  1109. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  1110. require.Equal(t, 200, response.Code)
  1111. m := toMessage(t, response.Body.String())
  1112. require.Equal(t, notification, m.Message)
  1113. }
  1114. func TestServer_MatrixGateway_Push_Failure_NoSubscriber(t *testing.T) {
  1115. c := newTestConfig(t)
  1116. c.VisitorSubscriberRateLimiting = true
  1117. s := newTestServer(t, c)
  1118. notification := `{"notification":{"devices":[{"pushkey":"http://127.0.0.1:12345/mytopic?up=1"}]}}`
  1119. response := request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1120. require.Equal(t, 507, response.Code)
  1121. require.Equal(t, 50701, toHTTPError(t, response.Body.String()).Code)
  1122. }
  1123. func TestServer_MatrixGateway_Push_Failure_NoSubscriber_After13Hours(t *testing.T) {
  1124. c := newTestConfig(t)
  1125. c.VisitorSubscriberRateLimiting = true
  1126. s := newTestServer(t, c)
  1127. notification := `{"notification":{"devices":[{"pushkey":"http://127.0.0.1:12345/mytopic?up=1"}]}}`
  1128. // No success if no rate visitor set (this also creates the topic in memory
  1129. response := request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1130. require.Equal(t, 507, response.Code)
  1131. require.Equal(t, 50701, toHTTPError(t, response.Body.String()).Code)
  1132. require.Nil(t, s.topics["mytopic"].rateVisitor)
  1133. // Fake: This topic has been around for 13 hours without a rate visitor
  1134. s.topics["mytopic"].lastAccess = time.Now().Add(-13 * time.Hour)
  1135. // Same request should now return HTTP 200 with a rejected pushkey
  1136. response = request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1137. require.Equal(t, 200, response.Code)
  1138. require.Equal(t, `{"rejected":["http://127.0.0.1:12345/mytopic?up=1"]}`, strings.TrimSpace(response.Body.String()))
  1139. // Slightly unrelated: Test that topic is pruned after 16 hours
  1140. s.topics["mytopic"].lastAccess = time.Now().Add(-17 * time.Hour)
  1141. s.execManager()
  1142. require.Nil(t, s.topics["mytopic"])
  1143. }
  1144. func TestServer_MatrixGateway_Push_Failure_InvalidPushkey(t *testing.T) {
  1145. s := newTestServer(t, newTestConfig(t))
  1146. notification := `{"notification":{"devices":[{"pushkey":"http://wrong-base-url.com/mytopic?up=1"}]}}`
  1147. response := request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1148. require.Equal(t, 200, response.Code)
  1149. require.Equal(t, `{"rejected":["http://wrong-base-url.com/mytopic?up=1"]}`+"\n", response.Body.String())
  1150. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  1151. require.Equal(t, 200, response.Code)
  1152. require.Equal(t, "", response.Body.String()) // Empty!
  1153. }
  1154. func TestServer_MatrixGateway_Push_Failure_EverythingIsWrong(t *testing.T) {
  1155. s := newTestServer(t, newTestConfig(t))
  1156. notification := `{"message":"this is not really a Matrix message"}`
  1157. response := request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1158. require.Equal(t, 400, response.Code)
  1159. require.Equal(t, 40019, toHTTPError(t, response.Body.String()).Code)
  1160. notification = `this isn't even JSON'`
  1161. response = request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1162. require.Equal(t, 400, response.Code)
  1163. require.Equal(t, 40019, toHTTPError(t, response.Body.String()).Code)
  1164. }
  1165. func TestServer_MatrixGateway_Push_Failure_Unconfigured(t *testing.T) {
  1166. c := newTestConfig(t)
  1167. c.BaseURL = ""
  1168. s := newTestServer(t, c)
  1169. notification := `{"notification":{"devices":[{"pushkey":"http://127.0.0.1:12345/mytopic?up=1"}]}}`
  1170. response := request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1171. require.Equal(t, 500, response.Code)
  1172. require.Equal(t, 50003, toHTTPError(t, response.Body.String()).Code)
  1173. }
  1174. func TestServer_PublishActions_AndPoll(t *testing.T) {
  1175. s := newTestServer(t, newTestConfig(t))
  1176. response := request(t, s, "PUT", "/mytopic", "my message", map[string]string{
  1177. "Actions": "view, Open portal, https://home.nest.com/; http, Turn down, https://api.nest.com/device/XZ1D2, body=target_temp_f=65",
  1178. })
  1179. require.Equal(t, 200, response.Code)
  1180. response = request(t, s, "GET", "/mytopic/json?poll=1", "", nil)
  1181. require.Equal(t, 200, response.Code)
  1182. m := toMessage(t, response.Body.String())
  1183. require.Equal(t, 2, len(m.Actions))
  1184. require.Equal(t, "view", m.Actions[0].Action)
  1185. require.Equal(t, "Open portal", m.Actions[0].Label)
  1186. require.Equal(t, "https://home.nest.com/", m.Actions[0].URL)
  1187. require.Equal(t, "http", m.Actions[1].Action)
  1188. require.Equal(t, "Turn down", m.Actions[1].Label)
  1189. require.Equal(t, "https://api.nest.com/device/XZ1D2", m.Actions[1].URL)
  1190. require.Equal(t, "target_temp_f=65", m.Actions[1].Body)
  1191. }
  1192. func TestServer_PublishAsJSON(t *testing.T) {
  1193. s := newTestServer(t, newTestConfig(t))
  1194. body := `{"topic":"mytopic","message":"A message","title":"a title\nwith lines","tags":["tag1","tag 2"],` +
  1195. `"not-a-thing":"ok", "attach":"http://google.com","filename":"google.pdf", "click":"http://ntfy.sh","priority":4,` +
  1196. `"icon":"https://ntfy.sh/static/img/ntfy.png", "delay":"30min"}`
  1197. response := request(t, s, "PUT", "/", body, nil)
  1198. require.Equal(t, 200, response.Code)
  1199. m := toMessage(t, response.Body.String())
  1200. require.Equal(t, "mytopic", m.Topic)
  1201. require.Equal(t, "A message", m.Message)
  1202. require.Equal(t, "a title\nwith lines", m.Title)
  1203. require.Equal(t, []string{"tag1", "tag 2"}, m.Tags)
  1204. require.Equal(t, "http://google.com", m.Attachment.URL)
  1205. require.Equal(t, "google.pdf", m.Attachment.Name)
  1206. require.Equal(t, "http://ntfy.sh", m.Click)
  1207. require.Equal(t, "https://ntfy.sh/static/img/ntfy.png", m.Icon)
  1208. require.Equal(t, 4, m.Priority)
  1209. require.True(t, m.Time > time.Now().Unix()+29*60)
  1210. require.True(t, m.Time < time.Now().Unix()+31*60)
  1211. }
  1212. func TestServer_PublishAsJSON_RateLimit_MessageDailyLimit(t *testing.T) {
  1213. // Publishing as JSON follows a different path. This ensures that rate
  1214. // limiting works for this endpoint as well
  1215. c := newTestConfig(t)
  1216. c.VisitorMessageDailyLimit = 3
  1217. s := newTestServer(t, c)
  1218. for i := 0; i < 3; i++ {
  1219. response := request(t, s, "PUT", "/", `{"topic":"mytopic","message":"A message"}`, nil)
  1220. require.Equal(t, 200, response.Code)
  1221. }
  1222. response := request(t, s, "PUT", "/", `{"topic":"mytopic","message":"A message"}`, nil)
  1223. require.Equal(t, 429, response.Code)
  1224. require.Equal(t, 42908, toHTTPError(t, response.Body.String()).Code)
  1225. }
  1226. func TestServer_PublishAsJSON_WithEmail(t *testing.T) {
  1227. t.Parallel()
  1228. mailer := &testMailer{}
  1229. s := newTestServer(t, newTestConfig(t))
  1230. s.smtpSender = mailer
  1231. body := `{"topic":"mytopic","message":"A message","email":"phil@example.com"}`
  1232. response := request(t, s, "PUT", "/", body, nil)
  1233. require.Equal(t, 200, response.Code)
  1234. time.Sleep(100 * time.Millisecond) // E-Mail publishing happens in a Go routine
  1235. m := toMessage(t, response.Body.String())
  1236. require.Equal(t, "mytopic", m.Topic)
  1237. require.Equal(t, "A message", m.Message)
  1238. require.Equal(t, 1, mailer.Count())
  1239. }
  1240. func TestServer_PublishAsJSON_WithActions(t *testing.T) {
  1241. s := newTestServer(t, newTestConfig(t))
  1242. body := `{
  1243. "topic":"mytopic",
  1244. "message":"A message",
  1245. "actions": [
  1246. {
  1247. "action": "view",
  1248. "label": "Open portal",
  1249. "url": "https://home.nest.com/"
  1250. },
  1251. {
  1252. "action": "http",
  1253. "label": "Turn down",
  1254. "url": "https://api.nest.com/device/XZ1D2",
  1255. "body": "target_temp_f=65"
  1256. }
  1257. ]
  1258. }`
  1259. response := request(t, s, "POST", "/", body, nil)
  1260. require.Equal(t, 200, response.Code)
  1261. m := toMessage(t, response.Body.String())
  1262. require.Equal(t, "mytopic", m.Topic)
  1263. require.Equal(t, "A message", m.Message)
  1264. require.Equal(t, 2, len(m.Actions))
  1265. require.Equal(t, "view", m.Actions[0].Action)
  1266. require.Equal(t, "Open portal", m.Actions[0].Label)
  1267. require.Equal(t, "https://home.nest.com/", m.Actions[0].URL)
  1268. require.Equal(t, "http", m.Actions[1].Action)
  1269. require.Equal(t, "Turn down", m.Actions[1].Label)
  1270. require.Equal(t, "https://api.nest.com/device/XZ1D2", m.Actions[1].URL)
  1271. require.Equal(t, "target_temp_f=65", m.Actions[1].Body)
  1272. }
  1273. func TestServer_PublishAsJSON_Invalid(t *testing.T) {
  1274. s := newTestServer(t, newTestConfig(t))
  1275. body := `{"topic":"mytopic",INVALID`
  1276. response := request(t, s, "PUT", "/", body, nil)
  1277. require.Equal(t, 400, response.Code)
  1278. }
  1279. func TestServer_PublishWithTierBasedMessageLimitAndExpiry(t *testing.T) {
  1280. c := newTestConfigWithAuthFile(t)
  1281. s := newTestServer(t, c)
  1282. // Create tier with certain limits
  1283. require.Nil(t, s.userManager.AddTier(&user.Tier{
  1284. Code: "test",
  1285. MessageLimit: 5,
  1286. MessageExpiryDuration: -5 * time.Second, // Second, what a hack!
  1287. }))
  1288. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser))
  1289. require.Nil(t, s.userManager.ChangeTier("phil", "test"))
  1290. // Publish to reach message limit
  1291. for i := 0; i < 5; i++ {
  1292. response := request(t, s, "PUT", "/mytopic", fmt.Sprintf("this is message %d", i+1), map[string]string{
  1293. "Authorization": util.BasicAuth("phil", "phil"),
  1294. })
  1295. require.Equal(t, 200, response.Code)
  1296. msg := toMessage(t, response.Body.String())
  1297. require.True(t, msg.Expires < time.Now().Unix()+5)
  1298. }
  1299. response := request(t, s, "PUT", "/mytopic", "this is too much", map[string]string{
  1300. "Authorization": util.BasicAuth("phil", "phil"),
  1301. })
  1302. require.Equal(t, 429, response.Code)
  1303. // Run pruning and see if they are gone
  1304. s.execManager()
  1305. response = request(t, s, "GET", "/mytopic/json?poll=1", "", map[string]string{
  1306. "Authorization": util.BasicAuth("phil", "phil"),
  1307. })
  1308. require.Equal(t, 200, response.Code)
  1309. require.Empty(t, response.Body)
  1310. }
  1311. func TestServer_PublishAttachment(t *testing.T) {
  1312. content := "text file!" + util.RandomString(4990) // > 4096
  1313. s := newTestServer(t, newTestConfig(t))
  1314. response := request(t, s, "PUT", "/mytopic", content, nil)
  1315. msg := toMessage(t, response.Body.String())
  1316. require.Equal(t, "attachment.txt", msg.Attachment.Name)
  1317. require.Equal(t, "text/plain; charset=utf-8", msg.Attachment.Type)
  1318. require.Equal(t, int64(5000), msg.Attachment.Size)
  1319. require.GreaterOrEqual(t, msg.Attachment.Expires, time.Now().Add(179*time.Minute).Unix()) // Almost 3 hours
  1320. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1321. require.Equal(t, netip.Addr{}, msg.Sender) // Should never be returned
  1322. require.FileExists(t, filepath.Join(s.config.AttachmentCacheDir, msg.ID))
  1323. // GET
  1324. path := strings.TrimPrefix(msg.Attachment.URL, "http://127.0.0.1:12345")
  1325. response = request(t, s, "GET", path, "", nil)
  1326. require.Equal(t, 200, response.Code)
  1327. require.Equal(t, "5000", response.Header().Get("Content-Length"))
  1328. require.Equal(t, content, response.Body.String())
  1329. // HEAD
  1330. response = request(t, s, "HEAD", path, "", nil)
  1331. require.Equal(t, 200, response.Code)
  1332. require.Equal(t, "5000", response.Header().Get("Content-Length"))
  1333. require.Equal(t, "", response.Body.String())
  1334. // Slightly unrelated cross-test: make sure we add an owner for internal attachments
  1335. size, err := s.messageCache.AttachmentBytesUsedBySender("9.9.9.9") // See request()
  1336. require.Nil(t, err)
  1337. require.Equal(t, int64(5000), size)
  1338. }
  1339. func TestServer_PublishAttachmentShortWithFilename(t *testing.T) {
  1340. c := newTestConfig(t)
  1341. c.BehindProxy = true
  1342. s := newTestServer(t, c)
  1343. content := "this is an ATTACHMENT"
  1344. response := request(t, s, "PUT", "/mytopic?f=myfile.txt", content, map[string]string{
  1345. "X-Forwarded-For": "1.2.3.4",
  1346. })
  1347. msg := toMessage(t, response.Body.String())
  1348. require.Equal(t, "myfile.txt", msg.Attachment.Name)
  1349. require.Equal(t, "text/plain; charset=utf-8", msg.Attachment.Type)
  1350. require.Equal(t, int64(21), msg.Attachment.Size)
  1351. require.GreaterOrEqual(t, msg.Attachment.Expires, time.Now().Add(3*time.Hour).Unix())
  1352. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1353. require.Equal(t, netip.Addr{}, msg.Sender) // Should never be returned
  1354. require.FileExists(t, filepath.Join(s.config.AttachmentCacheDir, msg.ID))
  1355. path := strings.TrimPrefix(msg.Attachment.URL, "http://127.0.0.1:12345")
  1356. response = request(t, s, "GET", path, "", nil)
  1357. require.Equal(t, 200, response.Code)
  1358. require.Equal(t, "21", response.Header().Get("Content-Length"))
  1359. require.Equal(t, content, response.Body.String())
  1360. // Slightly unrelated cross-test: make sure we add an owner for internal attachments
  1361. size, err := s.messageCache.AttachmentBytesUsedBySender("1.2.3.4")
  1362. require.Nil(t, err)
  1363. require.Equal(t, int64(21), size)
  1364. }
  1365. func TestServer_PublishAttachmentExternalWithoutFilename(t *testing.T) {
  1366. s := newTestServer(t, newTestConfig(t))
  1367. response := request(t, s, "PUT", "/mytopic", "", map[string]string{
  1368. "Attach": "https://upload.wikimedia.org/wikipedia/commons/f/fd/Pink_flower.jpg",
  1369. })
  1370. msg := toMessage(t, response.Body.String())
  1371. require.Equal(t, "You received a file: Pink_flower.jpg", msg.Message)
  1372. require.Equal(t, "Pink_flower.jpg", msg.Attachment.Name)
  1373. require.Equal(t, "https://upload.wikimedia.org/wikipedia/commons/f/fd/Pink_flower.jpg", msg.Attachment.URL)
  1374. require.Equal(t, "", msg.Attachment.Type)
  1375. require.Equal(t, int64(0), msg.Attachment.Size)
  1376. require.Equal(t, int64(0), msg.Attachment.Expires)
  1377. require.Equal(t, netip.Addr{}, msg.Sender)
  1378. // Slightly unrelated cross-test: make sure we don't add an owner for external attachments
  1379. size, err := s.messageCache.AttachmentBytesUsedBySender("127.0.0.1")
  1380. require.Nil(t, err)
  1381. require.Equal(t, int64(0), size)
  1382. }
  1383. func TestServer_PublishAttachmentExternalWithFilename(t *testing.T) {
  1384. s := newTestServer(t, newTestConfig(t))
  1385. response := request(t, s, "PUT", "/mytopic", "This is a custom message", map[string]string{
  1386. "X-Attach": "https://upload.wikimedia.org/wikipedia/commons/f/fd/Pink_flower.jpg",
  1387. "File": "some file.jpg",
  1388. })
  1389. msg := toMessage(t, response.Body.String())
  1390. require.Equal(t, "This is a custom message", msg.Message)
  1391. require.Equal(t, "some file.jpg", msg.Attachment.Name)
  1392. require.Equal(t, "https://upload.wikimedia.org/wikipedia/commons/f/fd/Pink_flower.jpg", msg.Attachment.URL)
  1393. require.Equal(t, "", msg.Attachment.Type)
  1394. require.Equal(t, int64(0), msg.Attachment.Size)
  1395. require.Equal(t, int64(0), msg.Attachment.Expires)
  1396. require.Equal(t, netip.Addr{}, msg.Sender)
  1397. }
  1398. func TestServer_PublishAttachmentBadURL(t *testing.T) {
  1399. s := newTestServer(t, newTestConfig(t))
  1400. response := request(t, s, "PUT", "/mytopic?a=not+a+URL", "", nil)
  1401. err := toHTTPError(t, response.Body.String())
  1402. require.Equal(t, 400, response.Code)
  1403. require.Equal(t, 400, err.HTTPCode)
  1404. require.Equal(t, 40013, err.Code)
  1405. }
  1406. func TestServer_PublishAttachmentTooLargeContentLength(t *testing.T) {
  1407. content := util.RandomString(5000) // > 4096
  1408. s := newTestServer(t, newTestConfig(t))
  1409. response := request(t, s, "PUT", "/mytopic", content, map[string]string{
  1410. "Content-Length": "20000000",
  1411. })
  1412. err := toHTTPError(t, response.Body.String())
  1413. require.Equal(t, 413, response.Code)
  1414. require.Equal(t, 413, err.HTTPCode)
  1415. require.Equal(t, 41301, err.Code)
  1416. }
  1417. func TestServer_PublishAttachmentTooLargeBodyAttachmentFileSizeLimit(t *testing.T) {
  1418. content := util.RandomString(5001) // > 5000, see below
  1419. c := newTestConfig(t)
  1420. c.AttachmentFileSizeLimit = 5000
  1421. s := newTestServer(t, c)
  1422. response := request(t, s, "PUT", "/mytopic", content, nil)
  1423. err := toHTTPError(t, response.Body.String())
  1424. require.Equal(t, 413, response.Code)
  1425. require.Equal(t, 413, err.HTTPCode)
  1426. require.Equal(t, 41301, err.Code)
  1427. }
  1428. func TestServer_PublishAttachmentExpiryBeforeDelivery(t *testing.T) {
  1429. c := newTestConfig(t)
  1430. c.AttachmentExpiryDuration = 10 * time.Minute
  1431. s := newTestServer(t, c)
  1432. response := request(t, s, "PUT", "/mytopic", util.RandomString(5000), map[string]string{
  1433. "Delay": "11 min", // > AttachmentExpiryDuration
  1434. })
  1435. err := toHTTPError(t, response.Body.String())
  1436. require.Equal(t, 400, response.Code)
  1437. require.Equal(t, 400, err.HTTPCode)
  1438. require.Equal(t, 40015, err.Code)
  1439. }
  1440. func TestServer_PublishAttachmentTooLargeBodyVisitorAttachmentTotalSizeLimit(t *testing.T) {
  1441. c := newTestConfig(t)
  1442. c.VisitorAttachmentTotalSizeLimit = 10000
  1443. s := newTestServer(t, c)
  1444. response := request(t, s, "PUT", "/mytopic", "text file!"+util.RandomString(4990), nil)
  1445. msg := toMessage(t, response.Body.String())
  1446. require.Equal(t, 200, response.Code)
  1447. require.Equal(t, "You received a file: attachment.txt", msg.Message)
  1448. require.Equal(t, int64(5000), msg.Attachment.Size)
  1449. content := util.RandomString(5001) // 5000+5001 > , see below
  1450. response = request(t, s, "PUT", "/mytopic", content, nil)
  1451. err := toHTTPError(t, response.Body.String())
  1452. require.Equal(t, 413, response.Code)
  1453. require.Equal(t, 413, err.HTTPCode)
  1454. require.Equal(t, 41301, err.Code)
  1455. }
  1456. func TestServer_PublishAttachmentAndExpire(t *testing.T) {
  1457. t.Parallel()
  1458. content := util.RandomString(5000) // > 4096
  1459. c := newTestConfig(t)
  1460. c.AttachmentExpiryDuration = time.Millisecond // Hack
  1461. s := newTestServer(t, c)
  1462. // Publish and make sure we can retrieve it
  1463. response := request(t, s, "PUT", "/mytopic", content, nil)
  1464. msg := toMessage(t, response.Body.String())
  1465. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1466. file := filepath.Join(s.config.AttachmentCacheDir, msg.ID)
  1467. require.FileExists(t, file)
  1468. path := strings.TrimPrefix(msg.Attachment.URL, "http://127.0.0.1:12345")
  1469. response = request(t, s, "GET", path, "", nil)
  1470. require.Equal(t, 200, response.Code)
  1471. require.Equal(t, content, response.Body.String())
  1472. // Prune and makes sure it's gone
  1473. waitFor(t, func() bool {
  1474. s.execManager() // May run many times
  1475. return !util.FileExists(file)
  1476. })
  1477. response = request(t, s, "GET", path, "", nil)
  1478. require.Equal(t, 404, response.Code)
  1479. }
  1480. func TestServer_PublishAttachmentWithTierBasedExpiry(t *testing.T) {
  1481. t.Parallel()
  1482. content := util.RandomString(5000) // > 4096
  1483. c := newTestConfigWithAuthFile(t)
  1484. c.AttachmentExpiryDuration = time.Millisecond // Hack
  1485. s := newTestServer(t, c)
  1486. // Create tier with certain limits
  1487. sevenDays := time.Duration(604800) * time.Second
  1488. require.Nil(t, s.userManager.AddTier(&user.Tier{
  1489. Code: "test",
  1490. MessageLimit: 10,
  1491. MessageExpiryDuration: sevenDays,
  1492. AttachmentFileSizeLimit: 50_000,
  1493. AttachmentTotalSizeLimit: 200_000,
  1494. AttachmentExpiryDuration: sevenDays, // 7 days
  1495. AttachmentBandwidthLimit: 100000,
  1496. }))
  1497. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser))
  1498. require.Nil(t, s.userManager.ChangeTier("phil", "test"))
  1499. // Publish and make sure we can retrieve it
  1500. response := request(t, s, "PUT", "/mytopic", content, map[string]string{
  1501. "Authorization": util.BasicAuth("phil", "phil"),
  1502. })
  1503. require.Equal(t, 200, response.Code)
  1504. msg := toMessage(t, response.Body.String())
  1505. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1506. require.True(t, msg.Attachment.Expires > time.Now().Add(sevenDays-30*time.Second).Unix())
  1507. require.True(t, msg.Expires > time.Now().Add(sevenDays-30*time.Second).Unix())
  1508. file := filepath.Join(s.config.AttachmentCacheDir, msg.ID)
  1509. require.FileExists(t, file)
  1510. path := strings.TrimPrefix(msg.Attachment.URL, "http://127.0.0.1:12345")
  1511. response = request(t, s, "GET", path, "", nil)
  1512. require.Equal(t, 200, response.Code)
  1513. require.Equal(t, content, response.Body.String())
  1514. // Prune and makes sure it's still there
  1515. time.Sleep(time.Second) // Sigh ...
  1516. s.execManager()
  1517. require.FileExists(t, file)
  1518. response = request(t, s, "GET", path, "", nil)
  1519. require.Equal(t, 200, response.Code)
  1520. }
  1521. func TestServer_PublishAttachmentWithTierBasedBandwidthLimit(t *testing.T) {
  1522. content := util.RandomString(5000) // > 4096
  1523. c := newTestConfigWithAuthFile(t)
  1524. c.VisitorAttachmentDailyBandwidthLimit = 1000 // Much lower than tier bandwidth!
  1525. s := newTestServer(t, c)
  1526. // Create tier with certain limits
  1527. require.Nil(t, s.userManager.AddTier(&user.Tier{
  1528. Code: "test",
  1529. MessageLimit: 10,
  1530. MessageExpiryDuration: time.Hour,
  1531. AttachmentFileSizeLimit: 50_000,
  1532. AttachmentTotalSizeLimit: 200_000,
  1533. AttachmentExpiryDuration: time.Hour,
  1534. AttachmentBandwidthLimit: 14000, // < 3x5000 bytes -> enough for one upload, one download
  1535. }))
  1536. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser))
  1537. require.Nil(t, s.userManager.ChangeTier("phil", "test"))
  1538. // Publish and make sure we can retrieve it
  1539. rr := request(t, s, "PUT", "/mytopic", content, map[string]string{
  1540. "Authorization": util.BasicAuth("phil", "phil"),
  1541. })
  1542. require.Equal(t, 200, rr.Code)
  1543. msg := toMessage(t, rr.Body.String())
  1544. // Retrieve it (first time succeeds)
  1545. rr = request(t, s, "GET", "/file/"+msg.ID, content, nil) // File downloads do not send auth headers!!
  1546. require.Equal(t, 200, rr.Code)
  1547. require.Equal(t, content, rr.Body.String())
  1548. // Retrieve it AGAIN (fails, due to bandwidth limit)
  1549. rr = request(t, s, "GET", "/file/"+msg.ID, content, nil)
  1550. require.Equal(t, 429, rr.Code)
  1551. }
  1552. func TestServer_PublishAttachmentWithTierBasedLimits(t *testing.T) {
  1553. smallFile := util.RandomString(20_000)
  1554. largeFile := util.RandomString(50_000)
  1555. c := newTestConfigWithAuthFile(t)
  1556. c.AttachmentFileSizeLimit = 20_000
  1557. c.VisitorAttachmentTotalSizeLimit = 40_000
  1558. s := newTestServer(t, c)
  1559. // Create tier with certain limits
  1560. require.Nil(t, s.userManager.AddTier(&user.Tier{
  1561. Code: "test",
  1562. MessageLimit: 100,
  1563. AttachmentFileSizeLimit: 50_000,
  1564. AttachmentTotalSizeLimit: 200_000,
  1565. AttachmentExpiryDuration: 30 * time.Second,
  1566. AttachmentBandwidthLimit: 1000000,
  1567. }))
  1568. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser))
  1569. require.Nil(t, s.userManager.ChangeTier("phil", "test"))
  1570. // Publish small file as anonymous
  1571. response := request(t, s, "PUT", "/mytopic", smallFile, nil)
  1572. msg := toMessage(t, response.Body.String())
  1573. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1574. require.FileExists(t, filepath.Join(s.config.AttachmentCacheDir, msg.ID))
  1575. // Publish large file as anonymous
  1576. response = request(t, s, "PUT", "/mytopic", largeFile, nil)
  1577. require.Equal(t, 413, response.Code)
  1578. require.Equal(t, 41301, toHTTPError(t, response.Body.String()).Code)
  1579. // Publish too large file as phil
  1580. response = request(t, s, "PUT", "/mytopic", largeFile+" a few more bytes", map[string]string{
  1581. "Authorization": util.BasicAuth("phil", "phil"),
  1582. })
  1583. require.Equal(t, 413, response.Code)
  1584. require.Equal(t, 41301, toHTTPError(t, response.Body.String()).Code)
  1585. // Publish large file as phil (4x)
  1586. for i := 0; i < 4; i++ {
  1587. response = request(t, s, "PUT", "/mytopic", largeFile, map[string]string{
  1588. "Authorization": util.BasicAuth("phil", "phil"),
  1589. })
  1590. require.Equal(t, 200, response.Code)
  1591. msg = toMessage(t, response.Body.String())
  1592. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1593. require.FileExists(t, filepath.Join(s.config.AttachmentCacheDir, msg.ID))
  1594. }
  1595. response = request(t, s, "PUT", "/mytopic", largeFile, map[string]string{
  1596. "Authorization": util.BasicAuth("phil", "phil"),
  1597. })
  1598. require.Equal(t, 413, response.Code)
  1599. require.Equal(t, 41301, toHTTPError(t, response.Body.String()).Code)
  1600. }
  1601. func TestServer_PublishAttachmentBandwidthLimit(t *testing.T) {
  1602. content := util.RandomString(5000) // > 4096
  1603. c := newTestConfig(t)
  1604. c.VisitorAttachmentDailyBandwidthLimit = 5*5000 + 123 // A little more than 1 upload and 3 downloads
  1605. s := newTestServer(t, c)
  1606. // Publish attachment
  1607. response := request(t, s, "PUT", "/mytopic", content, nil)
  1608. msg := toMessage(t, response.Body.String())
  1609. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1610. // Value it 4 times successfully
  1611. path := strings.TrimPrefix(msg.Attachment.URL, "http://127.0.0.1:12345")
  1612. for i := 1; i <= 4; i++ { // 4 successful downloads
  1613. response = request(t, s, "GET", path, "", nil)
  1614. require.Equal(t, 200, response.Code)
  1615. require.Equal(t, content, response.Body.String())
  1616. }
  1617. // And then fail with a 429
  1618. response = request(t, s, "GET", path, "", nil)
  1619. err := toHTTPError(t, response.Body.String())
  1620. require.Equal(t, 429, response.Code)
  1621. require.Equal(t, 42905, err.Code)
  1622. }
  1623. func TestServer_PublishAttachmentBandwidthLimitUploadOnly(t *testing.T) {
  1624. content := util.RandomString(5000) // > 4096
  1625. c := newTestConfig(t)
  1626. c.VisitorAttachmentDailyBandwidthLimit = 5*5000 + 500 // 5 successful uploads
  1627. s := newTestServer(t, c)
  1628. // 5 successful uploads
  1629. for i := 1; i <= 5; i++ {
  1630. response := request(t, s, "PUT", "/mytopic", content, nil)
  1631. msg := toMessage(t, response.Body.String())
  1632. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1633. }
  1634. // And a failed one
  1635. response := request(t, s, "PUT", "/mytopic", content, nil)
  1636. err := toHTTPError(t, response.Body.String())
  1637. require.Equal(t, 413, response.Code)
  1638. require.Equal(t, 41301, err.Code)
  1639. }
  1640. func TestServer_PublishAttachmentAndImmediatelyGetItWithCacheTimeout(t *testing.T) {
  1641. // This tests the awkward util.Retry in handleFile: Due to the async persisting of messages,
  1642. // the message is not immediately available when attempting to download it.
  1643. c := newTestConfig(t)
  1644. c.CacheBatchTimeout = 500 * time.Millisecond
  1645. c.CacheBatchSize = 10
  1646. s := newTestServer(t, c)
  1647. content := "this is an ATTACHMENT"
  1648. rr := request(t, s, "PUT", "/mytopic?f=myfile.txt", content, nil)
  1649. m := toMessage(t, rr.Body.String())
  1650. require.Equal(t, "myfile.txt", m.Attachment.Name)
  1651. path := strings.TrimPrefix(m.Attachment.URL, "http://127.0.0.1:12345")
  1652. rr = request(t, s, "GET", path, "", nil)
  1653. require.Equal(t, 200, rr.Code) // Not 404!
  1654. require.Equal(t, content, rr.Body.String())
  1655. }
  1656. func TestServer_PublishAttachmentAccountStats(t *testing.T) {
  1657. content := util.RandomString(4999) // > 4096
  1658. c := newTestConfig(t)
  1659. c.AttachmentFileSizeLimit = 5000
  1660. c.VisitorAttachmentTotalSizeLimit = 6000
  1661. s := newTestServer(t, c)
  1662. // Upload one attachment
  1663. response := request(t, s, "PUT", "/mytopic", content, nil)
  1664. msg := toMessage(t, response.Body.String())
  1665. require.Contains(t, msg.Attachment.URL, "http://127.0.0.1:12345/file/")
  1666. // User stats
  1667. response = request(t, s, "GET", "/v1/account", "", nil)
  1668. require.Equal(t, 200, response.Code)
  1669. account, err := util.UnmarshalJSON[apiAccountResponse](io.NopCloser(response.Body))
  1670. require.Nil(t, err)
  1671. require.Equal(t, int64(5000), account.Limits.AttachmentFileSize)
  1672. require.Equal(t, int64(6000), account.Limits.AttachmentTotalSize)
  1673. require.Equal(t, int64(4999), account.Stats.AttachmentTotalSize)
  1674. require.Equal(t, int64(1001), account.Stats.AttachmentTotalSizeRemaining)
  1675. require.Equal(t, int64(1), account.Stats.Messages)
  1676. }
  1677. func TestServer_Visitor_XForwardedFor_None(t *testing.T) {
  1678. c := newTestConfig(t)
  1679. c.BehindProxy = true
  1680. s := newTestServer(t, c)
  1681. r, _ := http.NewRequest("GET", "/bla", nil)
  1682. r.RemoteAddr = "8.9.10.11"
  1683. r.Header.Set("X-Forwarded-For", " ") // Spaces, not empty!
  1684. v, err := s.maybeAuthenticate(r)
  1685. require.Nil(t, err)
  1686. require.Equal(t, "8.9.10.11", v.ip.String())
  1687. }
  1688. func TestServer_Visitor_XForwardedFor_Single(t *testing.T) {
  1689. c := newTestConfig(t)
  1690. c.BehindProxy = true
  1691. s := newTestServer(t, c)
  1692. r, _ := http.NewRequest("GET", "/bla", nil)
  1693. r.RemoteAddr = "8.9.10.11"
  1694. r.Header.Set("X-Forwarded-For", "1.1.1.1")
  1695. v, err := s.maybeAuthenticate(r)
  1696. require.Nil(t, err)
  1697. require.Equal(t, "1.1.1.1", v.ip.String())
  1698. }
  1699. func TestServer_Visitor_XForwardedFor_Multiple(t *testing.T) {
  1700. c := newTestConfig(t)
  1701. c.BehindProxy = true
  1702. s := newTestServer(t, c)
  1703. r, _ := http.NewRequest("GET", "/bla", nil)
  1704. r.RemoteAddr = "8.9.10.11"
  1705. r.Header.Set("X-Forwarded-For", "1.2.3.4 , 2.4.4.2,234.5.2.1 ")
  1706. v, err := s.maybeAuthenticate(r)
  1707. require.Nil(t, err)
  1708. require.Equal(t, "234.5.2.1", v.ip.String())
  1709. }
  1710. func TestServer_PublishWhileUpdatingStatsWithLotsOfMessages(t *testing.T) {
  1711. t.Parallel()
  1712. count := 50000
  1713. c := newTestConfig(t)
  1714. c.TotalTopicLimit = 50001
  1715. c.CacheStartupQueries = "pragma journal_mode = WAL; pragma synchronous = normal; pragma temp_store = memory;"
  1716. s := newTestServer(t, c)
  1717. // Add lots of messages
  1718. log.Info("Adding %d messages", count)
  1719. start := time.Now()
  1720. messages := make([]*message, 0)
  1721. for i := 0; i < count; i++ {
  1722. topicID := fmt.Sprintf("topic%d", i)
  1723. _, err := s.topicsFromIDs(topicID) // Add topic to internal s.topics array
  1724. require.Nil(t, err)
  1725. messages = append(messages, newDefaultMessage(topicID, "some message"))
  1726. }
  1727. require.Nil(t, s.messageCache.addMessages(messages))
  1728. log.Info("Done: Adding %d messages; took %s", count, time.Since(start).Round(time.Millisecond))
  1729. // Update stats
  1730. statsChan := make(chan bool)
  1731. go func() {
  1732. log.Info("Updating stats")
  1733. start := time.Now()
  1734. s.execManager()
  1735. log.Info("Done: Updating stats; took %s", time.Since(start).Round(time.Millisecond))
  1736. statsChan <- true
  1737. }()
  1738. time.Sleep(50 * time.Millisecond) // Make sure it starts first
  1739. // Publish message (during stats update)
  1740. log.Info("Publishing message")
  1741. start = time.Now()
  1742. response := request(t, s, "PUT", "/mytopic", "some body", nil)
  1743. m := toMessage(t, response.Body.String())
  1744. assert.Equal(t, "some body", m.Message)
  1745. assert.True(t, time.Since(start) < 100*time.Millisecond)
  1746. log.Info("Done: Publishing message; took %s", time.Since(start).Round(time.Millisecond))
  1747. // Wait for all goroutines
  1748. select {
  1749. case <-statsChan:
  1750. case <-time.After(10 * time.Second):
  1751. t.Fatal("Timed out waiting for Go routines")
  1752. }
  1753. log.Info("Done: Waiting for all locks")
  1754. }
  1755. func TestServer_AnonymousUser_And_NonTierUser_Are_Same_Visitor(t *testing.T) {
  1756. conf := newTestConfigWithAuthFile(t)
  1757. s := newTestServer(t, conf)
  1758. defer s.closeDatabases()
  1759. // Create user without tier
  1760. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser))
  1761. // Publish a message (anonymous user)
  1762. rr := request(t, s, "POST", "/mytopic", "hi", nil)
  1763. require.Equal(t, 200, rr.Code)
  1764. // Publish a message (non-tier user)
  1765. rr = request(t, s, "POST", "/mytopic", "hi", map[string]string{
  1766. "Authorization": util.BasicAuth("phil", "phil"),
  1767. })
  1768. require.Equal(t, 200, rr.Code)
  1769. // User stats (anonymous user)
  1770. rr = request(t, s, "GET", "/v1/account", "", nil)
  1771. account, _ := util.UnmarshalJSON[apiAccountResponse](io.NopCloser(rr.Body))
  1772. require.Equal(t, int64(2), account.Stats.Messages)
  1773. // User stats (non-tier user)
  1774. rr = request(t, s, "GET", "/v1/account", "", map[string]string{
  1775. "Authorization": util.BasicAuth("phil", "phil"),
  1776. })
  1777. account, _ = util.UnmarshalJSON[apiAccountResponse](io.NopCloser(rr.Body))
  1778. require.Equal(t, int64(2), account.Stats.Messages)
  1779. }
  1780. func TestServer_SubscriberRateLimiting_Success(t *testing.T) {
  1781. c := newTestConfigWithAuthFile(t)
  1782. c.VisitorRequestLimitBurst = 3
  1783. c.VisitorSubscriberRateLimiting = true
  1784. s := newTestServer(t, c)
  1785. // "Register" visitor 1.2.3.4 to topic "subscriber1topic" as a rate limit visitor
  1786. subscriber1Fn := func(r *http.Request) {
  1787. r.RemoteAddr = "1.2.3.4"
  1788. }
  1789. rr := request(t, s, "GET", "/subscriber1topic/json?poll=1", "", map[string]string{
  1790. "Rate-Topics": "subscriber1topic",
  1791. }, subscriber1Fn)
  1792. require.Equal(t, 200, rr.Code)
  1793. require.Equal(t, "", rr.Body.String())
  1794. require.Equal(t, "1.2.3.4", s.topics["subscriber1topic"].rateVisitor.ip.String())
  1795. // "Register" visitor 8.7.7.1 to topic "up012345678912" as a rate limit visitor (implicitly via topic name)
  1796. subscriber2Fn := func(r *http.Request) {
  1797. r.RemoteAddr = "8.7.7.1"
  1798. }
  1799. rr = request(t, s, "GET", "/up012345678912/json?poll=1", "", nil, subscriber2Fn)
  1800. require.Equal(t, 200, rr.Code)
  1801. require.Equal(t, "", rr.Body.String())
  1802. require.Equal(t, "8.7.7.1", s.topics["up012345678912"].rateVisitor.ip.String())
  1803. // Publish 2 messages to "subscriber1topic" as visitor 9.9.9.9. It'd be 3 normally, but the
  1804. // GET request before is also counted towards the request limiter.
  1805. for i := 0; i < 2; i++ {
  1806. rr := request(t, s, "PUT", "/subscriber1topic", "some message", nil)
  1807. require.Equal(t, 200, rr.Code)
  1808. }
  1809. rr = request(t, s, "PUT", "/subscriber1topic", "some message", nil)
  1810. require.Equal(t, 429, rr.Code)
  1811. // Publish another 2 messages to "up012345678912" as visitor 9.9.9.9
  1812. for i := 0; i < 2; i++ {
  1813. rr := request(t, s, "PUT", "/up012345678912", "some message", nil)
  1814. require.Equal(t, 200, rr.Code) // If we fail here, handlePublish is using the wrong visitor!
  1815. }
  1816. rr = request(t, s, "PUT", "/up012345678912", "some message", nil)
  1817. require.Equal(t, 429, rr.Code)
  1818. // Hurray! At this point, visitor 9.9.9.9 has published 4 messages, even though
  1819. // VisitorRequestLimitBurst is 3. That means it's working.
  1820. // Now let's confirm that so far we haven't used up any of visitor 9.9.9.9's request limiter
  1821. // by publishing another 3 requests from it.
  1822. for i := 0; i < 3; i++ {
  1823. rr := request(t, s, "PUT", "/some-other-topic", "some message", nil)
  1824. require.Equal(t, 200, rr.Code)
  1825. }
  1826. rr = request(t, s, "PUT", "/some-other-topic", "some message", nil)
  1827. require.Equal(t, 429, rr.Code)
  1828. }
  1829. func TestServer_SubscriberRateLimiting_NotEnabled_Failed(t *testing.T) {
  1830. c := newTestConfigWithAuthFile(t)
  1831. c.VisitorRequestLimitBurst = 3
  1832. c.VisitorSubscriberRateLimiting = false
  1833. s := newTestServer(t, c)
  1834. // Subscriber rate limiting is disabled!
  1835. // Registering visitor 1.2.3.4 to topic has no effect
  1836. rr := request(t, s, "GET", "/subscriber1topic/json?poll=1", "", map[string]string{
  1837. "Rate-Topics": "subscriber1topic",
  1838. }, func(r *http.Request) {
  1839. r.RemoteAddr = "1.2.3.4"
  1840. })
  1841. require.Equal(t, 200, rr.Code)
  1842. require.Equal(t, "", rr.Body.String())
  1843. require.Nil(t, s.topics["subscriber1topic"].rateVisitor)
  1844. // Registering visitor 8.7.7.1 to topic has no effect
  1845. rr = request(t, s, "GET", "/up012345678912/json?poll=1", "", nil, func(r *http.Request) {
  1846. r.RemoteAddr = "8.7.7.1"
  1847. })
  1848. require.Equal(t, 200, rr.Code)
  1849. require.Equal(t, "", rr.Body.String())
  1850. require.Nil(t, s.topics["up012345678912"].rateVisitor)
  1851. // Publish 3 messages to "subscriber1topic" as visitor 9.9.9.9
  1852. for i := 0; i < 3; i++ {
  1853. rr := request(t, s, "PUT", "/subscriber1topic", "some message", nil)
  1854. require.Equal(t, 200, rr.Code)
  1855. }
  1856. rr = request(t, s, "PUT", "/subscriber1topic", "some message", nil)
  1857. require.Equal(t, 429, rr.Code)
  1858. rr = request(t, s, "PUT", "/up012345678912", "some message", nil)
  1859. require.Equal(t, 429, rr.Code)
  1860. }
  1861. func TestServer_SubscriberRateLimiting_UP_Only(t *testing.T) {
  1862. c := newTestConfigWithAuthFile(t)
  1863. c.VisitorRequestLimitBurst = 3
  1864. c.VisitorSubscriberRateLimiting = true
  1865. s := newTestServer(t, c)
  1866. // "Register" 5 different UnifiedPush visitors
  1867. for i := 0; i < 5; i++ {
  1868. subscriberFn := func(r *http.Request) {
  1869. r.RemoteAddr = fmt.Sprintf("1.2.3.%d", i+1)
  1870. }
  1871. rr := request(t, s, "GET", fmt.Sprintf("/up12345678901%d/json?poll=1", i), "", nil, subscriberFn)
  1872. require.Equal(t, 200, rr.Code)
  1873. }
  1874. // Publish 2 messages per topic
  1875. for i := 0; i < 5; i++ {
  1876. for j := 0; j < 2; j++ {
  1877. rr := request(t, s, "PUT", fmt.Sprintf("/up12345678901%d?up=1", i), "some message", nil)
  1878. require.Equal(t, 200, rr.Code)
  1879. }
  1880. }
  1881. }
  1882. func TestServer_Matrix_SubscriberRateLimiting_UP_Only(t *testing.T) {
  1883. c := newTestConfig(t)
  1884. c.VisitorRequestLimitBurst = 3
  1885. c.VisitorSubscriberRateLimiting = true
  1886. s := newTestServer(t, c)
  1887. // "Register" 5 different UnifiedPush visitors
  1888. for i := 0; i < 5; i++ {
  1889. rr := request(t, s, "GET", fmt.Sprintf("/up12345678901%d/json?poll=1", i), "", nil, func(r *http.Request) {
  1890. r.RemoteAddr = fmt.Sprintf("1.2.3.%d", i+1)
  1891. })
  1892. require.Equal(t, 200, rr.Code)
  1893. }
  1894. // Publish 2 messages per topic
  1895. for i := 0; i < 5; i++ {
  1896. notification := fmt.Sprintf(`{"notification":{"devices":[{"pushkey":"http://127.0.0.1:12345/up12345678901%d?up=1"}]}}`, i)
  1897. for j := 0; j < 2; j++ {
  1898. response := request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1899. require.Equal(t, 200, response.Code)
  1900. require.Equal(t, `{"rejected":[]}`+"\n", response.Body.String())
  1901. }
  1902. response := request(t, s, "POST", "/_matrix/push/v1/notify", notification, nil)
  1903. require.Equal(t, 429, response.Code, notification)
  1904. require.Equal(t, 42901, toHTTPError(t, response.Body.String()).Code)
  1905. }
  1906. }
  1907. func TestServer_SubscriberRateLimiting_VisitorExpiration(t *testing.T) {
  1908. c := newTestConfig(t)
  1909. c.VisitorRequestLimitBurst = 3
  1910. c.VisitorSubscriberRateLimiting = true
  1911. s := newTestServer(t, c)
  1912. // "Register" rate visitor
  1913. subscriberFn := func(r *http.Request) {
  1914. r.RemoteAddr = "1.2.3.4"
  1915. }
  1916. rr := request(t, s, "GET", "/mytopic/json?poll=1", "", map[string]string{
  1917. "rate-topics": "mytopic",
  1918. }, subscriberFn)
  1919. require.Equal(t, 200, rr.Code)
  1920. require.Equal(t, "1.2.3.4", s.topics["mytopic"].rateVisitor.ip.String())
  1921. require.Equal(t, s.visitors["ip:1.2.3.4"], s.topics["mytopic"].rateVisitor)
  1922. // Publish message, observe rate visitor tokens being decreased
  1923. response := request(t, s, "POST", "/mytopic", "some message", nil)
  1924. require.Equal(t, 200, response.Code)
  1925. require.Equal(t, int64(0), s.visitors["ip:9.9.9.9"].messagesLimiter.Value())
  1926. require.Equal(t, int64(1), s.topics["mytopic"].rateVisitor.messagesLimiter.Value())
  1927. require.Equal(t, s.visitors["ip:1.2.3.4"], s.topics["mytopic"].rateVisitor)
  1928. // Expire visitor
  1929. s.visitors["ip:1.2.3.4"].seen = time.Now().Add(-1 * 25 * time.Hour)
  1930. s.pruneVisitors()
  1931. // Publish message again, observe that rateVisitor is not used anymore and is reset
  1932. response = request(t, s, "POST", "/mytopic", "some message", nil)
  1933. require.Equal(t, 200, response.Code)
  1934. require.Equal(t, int64(1), s.visitors["ip:9.9.9.9"].messagesLimiter.Value())
  1935. require.Nil(t, s.topics["mytopic"].rateVisitor)
  1936. require.Nil(t, s.visitors["ip:1.2.3.4"])
  1937. }
  1938. func TestServer_SubscriberRateLimiting_ProtectedTopics(t *testing.T) {
  1939. c := newTestConfigWithAuthFile(t)
  1940. c.AuthDefault = user.PermissionDenyAll
  1941. c.VisitorSubscriberRateLimiting = true
  1942. s := newTestServer(t, c)
  1943. // Create some ACLs
  1944. require.Nil(t, s.userManager.AddTier(&user.Tier{
  1945. Code: "test",
  1946. MessageLimit: 5,
  1947. }))
  1948. require.Nil(t, s.userManager.AddUser("ben", "ben", user.RoleUser))
  1949. require.Nil(t, s.userManager.ChangeTier("ben", "test"))
  1950. require.Nil(t, s.userManager.AllowAccess("ben", "announcements", user.PermissionReadWrite))
  1951. require.Nil(t, s.userManager.AllowAccess(user.Everyone, "announcements", user.PermissionRead))
  1952. require.Nil(t, s.userManager.AllowAccess(user.Everyone, "public_topic", user.PermissionReadWrite))
  1953. require.Nil(t, s.userManager.AddUser("phil", "phil", user.RoleUser))
  1954. require.Nil(t, s.userManager.ChangeTier("phil", "test"))
  1955. require.Nil(t, s.userManager.AddReservation("phil", "reserved-for-phil", user.PermissionReadWrite))
  1956. // Set rate visitor as user "phil" on topic
  1957. // - "reserved-for-phil": Allowed, because I am the owner
  1958. // - "public_topic": Allowed, because it has read-write permissions for everyone
  1959. // - "announcements": NOT allowed, because it has read-only permissions for everyone
  1960. rr := request(t, s, "GET", "/reserved-for-phil,public_topic,announcements/json?poll=1", "", map[string]string{
  1961. "Authorization": util.BasicAuth("phil", "phil"),
  1962. "Rate-Topics": "reserved-for-phil,public_topic,announcements",
  1963. })
  1964. require.Equal(t, 200, rr.Code)
  1965. require.Equal(t, "phil", s.topics["reserved-for-phil"].rateVisitor.user.Name)
  1966. require.Equal(t, "phil", s.topics["public_topic"].rateVisitor.user.Name)
  1967. require.Nil(t, s.topics["announcements"].rateVisitor)
  1968. // Set rate visitor as user "ben" on topic
  1969. // - "reserved-for-phil": NOT allowed, because I am not the owner
  1970. // - "public_topic": Allowed, because it has read-write permissions for everyone
  1971. // - "announcements": Allowed, because I have read-write permissions
  1972. rr = request(t, s, "GET", "/reserved-for-phil,public_topic,announcements/json?poll=1", "", map[string]string{
  1973. "Authorization": util.BasicAuth("ben", "ben"),
  1974. "Rate-Topics": "reserved-for-phil,public_topic,announcements",
  1975. })
  1976. require.Equal(t, 200, rr.Code)
  1977. require.Equal(t, "phil", s.topics["reserved-for-phil"].rateVisitor.user.Name)
  1978. require.Equal(t, "ben", s.topics["public_topic"].rateVisitor.user.Name)
  1979. require.Equal(t, "ben", s.topics["announcements"].rateVisitor.user.Name)
  1980. }
  1981. func TestServer_SubscriberRateLimiting_ProtectedTopics_WithDefaultReadWrite(t *testing.T) {
  1982. c := newTestConfigWithAuthFile(t)
  1983. c.AuthDefault = user.PermissionReadWrite
  1984. c.VisitorSubscriberRateLimiting = true
  1985. s := newTestServer(t, c)
  1986. // Create some ACLs
  1987. require.Nil(t, s.userManager.AllowAccess(user.Everyone, "announcements", user.PermissionRead))
  1988. // Set rate visitor as ip:1.2.3.4 on topic
  1989. // - "up123456789012": Allowed, because no ACLs and nobody owns the topic
  1990. // - "announcements": NOT allowed, because it has read-only permissions for everyone
  1991. rr := request(t, s, "GET", "/up123456789012,announcements/json?poll=1", "", nil, func(r *http.Request) {
  1992. r.RemoteAddr = "1.2.3.4"
  1993. })
  1994. require.Equal(t, 200, rr.Code)
  1995. require.Equal(t, "1.2.3.4", s.topics["up123456789012"].rateVisitor.ip.String())
  1996. require.Nil(t, s.topics["announcements"].rateVisitor)
  1997. }
  1998. func newTestConfig(t *testing.T) *Config {
  1999. conf := NewConfig()
  2000. conf.BaseURL = "http://127.0.0.1:12345"
  2001. conf.CacheFile = filepath.Join(t.TempDir(), "cache.db")
  2002. conf.CacheStartupQueries = "pragma journal_mode = WAL; pragma synchronous = normal; pragma temp_store = memory;"
  2003. conf.AttachmentCacheDir = t.TempDir()
  2004. return conf
  2005. }
  2006. func newTestConfigWithAuthFile(t *testing.T) *Config {
  2007. conf := newTestConfig(t)
  2008. conf.AuthFile = filepath.Join(t.TempDir(), "user.db")
  2009. conf.AuthStartupQueries = "pragma journal_mode = WAL; pragma synchronous = normal; pragma temp_store = memory;"
  2010. conf.AuthBcryptCost = bcrypt.MinCost // This speeds up tests a lot
  2011. return conf
  2012. }
  2013. func newTestServer(t *testing.T, config *Config) *Server {
  2014. server, err := New(config)
  2015. if err != nil {
  2016. t.Fatal(err)
  2017. }
  2018. return server
  2019. }
  2020. func request(t *testing.T, s *Server, method, url, body string, headers map[string]string, fn ...func(r *http.Request)) *httptest.ResponseRecorder {
  2021. rr := httptest.NewRecorder()
  2022. r, err := http.NewRequest(method, url, strings.NewReader(body))
  2023. if err != nil {
  2024. t.Fatal(err)
  2025. }
  2026. r.RemoteAddr = "9.9.9.9" // Used for tests
  2027. for k, v := range headers {
  2028. r.Header.Set(k, v)
  2029. }
  2030. for _, f := range fn {
  2031. f(r)
  2032. }
  2033. s.handle(rr, r)
  2034. return rr
  2035. }
  2036. func subscribe(t *testing.T, s *Server, url string, rr *httptest.ResponseRecorder) context.CancelFunc {
  2037. ctx, cancel := context.WithCancel(context.Background())
  2038. req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
  2039. if err != nil {
  2040. t.Fatal(err)
  2041. }
  2042. done := make(chan bool)
  2043. go func() {
  2044. s.handle(rr, req)
  2045. done <- true
  2046. }()
  2047. cancelAndWaitForDone := func() {
  2048. time.Sleep(200 * time.Millisecond)
  2049. cancel()
  2050. <-done
  2051. }
  2052. time.Sleep(200 * time.Millisecond)
  2053. return cancelAndWaitForDone
  2054. }
  2055. func toMessages(t *testing.T, s string) []*message {
  2056. messages := make([]*message, 0)
  2057. scanner := bufio.NewScanner(strings.NewReader(s))
  2058. for scanner.Scan() {
  2059. messages = append(messages, toMessage(t, scanner.Text()))
  2060. }
  2061. return messages
  2062. }
  2063. func toMessage(t *testing.T, s string) *message {
  2064. var m message
  2065. require.Nil(t, json.NewDecoder(strings.NewReader(s)).Decode(&m))
  2066. return &m
  2067. }
  2068. func toHTTPError(t *testing.T, s string) *errHTTP {
  2069. var e errHTTP
  2070. require.Nil(t, json.NewDecoder(strings.NewReader(s)).Decode(&e))
  2071. return &e
  2072. }
  2073. func readAll(t *testing.T, rc io.ReadCloser) string {
  2074. b, err := io.ReadAll(rc)
  2075. if err != nil {
  2076. t.Fatal(err)
  2077. }
  2078. return string(b)
  2079. }
  2080. func waitFor(t *testing.T, f func() bool) {
  2081. waitForWithMaxWait(t, 5*time.Second, f)
  2082. }
  2083. func waitForWithMaxWait(t *testing.T, maxWait time.Duration, f func() bool) {
  2084. start := time.Now()
  2085. for time.Since(start) < maxWait {
  2086. if f() {
  2087. return
  2088. }
  2089. time.Sleep(100 * time.Millisecond)
  2090. }
  2091. t.Fatalf("Function f did not succeed after %v: %v", maxWait, string(debug.Stack()))
  2092. }