server_test.go 93 KB

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