session_test.go 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148
  1. package webapi
  2. import (
  3. "context"
  4. "encoding/hex"
  5. "fmt"
  6. "io"
  7. "log/slog"
  8. "testing"
  9. "time"
  10. "github.com/stretchr/testify/assert"
  11. "github.com/stretchr/testify/require"
  12. "github.com/mk6i/open-oscar-server/state"
  13. "github.com/mk6i/open-oscar-server/wire"
  14. )
  15. func TestSession_IsExpired(t *testing.T) {
  16. tests := []struct {
  17. name string
  18. expiresAt time.Time
  19. isExpired bool
  20. }{
  21. {
  22. name: "Not_Expired",
  23. expiresAt: time.Now().Add(time.Hour),
  24. isExpired: false,
  25. },
  26. {
  27. name: "Already_Expired",
  28. expiresAt: time.Now().Add(-time.Hour),
  29. isExpired: true,
  30. },
  31. {
  32. name: "Just_Expired",
  33. expiresAt: time.Now().Add(-time.Second),
  34. isExpired: true,
  35. },
  36. }
  37. for _, tt := range tests {
  38. t.Run(tt.name, func(t *testing.T) {
  39. session := &Session{
  40. AimSID: "test-session",
  41. ScreenName: state.DisplayScreenName("testuser"),
  42. ExpiresAt: tt.expiresAt,
  43. }
  44. assert.Equal(t, tt.isExpired, session.IsExpired())
  45. })
  46. }
  47. }
  48. func TestSessionManager_ShutdownIdempotent(t *testing.T) {
  49. mgr := NewSessionManager()
  50. _ = mgr.Shutdown(context.Background())
  51. assert.NotPanics(t, func() {
  52. _ = mgr.Shutdown(context.Background())
  53. })
  54. }
  55. // TestSessionManager_CreateAfterShutdown verifies that a session cannot be
  56. // created once the manager is shut down. Otherwise the reaper is stopped and the
  57. // session would never be closed or reaped, leaking its OSCAR session.
  58. func TestSessionManager_CreateAfterShutdown(t *testing.T) {
  59. mgr := NewSessionManager()
  60. _ = mgr.Shutdown(context.Background())
  61. sess, err := mgr.CreateSession(state.DisplayScreenName("testuser"), []string{"presence"}, nil, "", nil)
  62. assert.Nil(t, sess)
  63. assert.ErrorIs(t, err, ErrWebAPISessionManagerClosed)
  64. }
  65. // A broadcast rate limit SNAC surfaces to the client only for the IM class: the
  66. // web client renders any rateLimit event as the conversation-window alert. Code 1
  67. // (a class-params change) is not a status transition and is dropped.
  68. func TestSession_handleRateLimitUpdate(t *testing.T) {
  69. const imClass = wire.RateLimitClassID(3)
  70. newSession := func() *Session {
  71. return &Session{
  72. IMRateClassID: imClass,
  73. EventQueue: NewEventQueue(10),
  74. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  75. FeedbagLoader: emptyFeedbagLoader,
  76. }
  77. }
  78. rateSNAC := func(classID uint16, code uint16) wire.SNACMessage {
  79. return wire.SNACMessage{
  80. Frame: wire.SNACFrame{FoodGroup: wire.OService, SubGroup: wire.OServiceRateParamChange},
  81. Body: wire.SNAC_0x01_0x0A_OServiceRateParamsChange{Code: code, Rate: wire.RateParamsSNAC{ID: classID}},
  82. }
  83. }
  84. t.Run("IM-class transitions become rateLimit events", func(t *testing.T) {
  85. sess := newSession()
  86. sess.handleSNACMessage(rateSNAC(uint16(imClass), 3)) // limited
  87. sess.handleSNACMessage(rateSNAC(uint16(imClass), 4)) // clear
  88. events := sess.EventQueue.GetAllEvents()
  89. require.Len(t, events, 2)
  90. assert.Equal(t, "limit", events[0].Data.(RateLimitEvent).Classes[0].Status)
  91. assert.Equal(t, "clear", events[1].Data.(RateLimitEvent).Classes[0].Status)
  92. })
  93. t.Run("other classes and non-status codes are ignored", func(t *testing.T) {
  94. sess := newSession()
  95. sess.handleSNACMessage(rateSNAC(1, 3)) // class 1 limited: not the IM class
  96. sess.handleSNACMessage(rateSNAC(uint16(imClass), 1)) // IM class param change, not a status
  97. assert.Empty(t, sess.EventQueue.GetAllEvents())
  98. })
  99. t.Run("a session with no IM class disables the alert", func(t *testing.T) {
  100. sess := newSession()
  101. sess.IMRateClassID = 0
  102. sess.handleSNACMessage(rateSNAC(uint16(imClass), 3))
  103. assert.Empty(t, sess.EventQueue.GetAllEvents())
  104. })
  105. }
  106. // A rate-limit disconnect closes the account's OSCAR session; the web session's
  107. // aimsid must then stop resolving. Before this fix GetSession only checked
  108. // time-based expiry, so a client told to disconnect could keep issuing charged
  109. // requests against a dead session (and, downstream, spam clear events on every
  110. // one of them). Once the aimsid is turned away at RequireSession, neither is
  111. // possible.
  112. func TestSessionManager_GetSession_rejectsAfterRateLimitDisconnect(t *testing.T) {
  113. mgr := NewSessionManager()
  114. // A rate class that escalates to disconnect after a short back-to-back burst.
  115. var classes [5]wire.RateClass
  116. for i := range classes {
  117. classes[i] = wire.RateClass{
  118. ID: wire.RateLimitClassID(i + 1),
  119. WindowSize: 2,
  120. ClearLevel: 100,
  121. AlertLevel: 80,
  122. LimitLevel: 70,
  123. DisconnectLevel: 2,
  124. MaxLevel: 200,
  125. }
  126. }
  127. inst := state.NewSession().AddInstance()
  128. inst.Session().SetRateClasses(time.Now(), wire.NewRateLimitClasses(classes))
  129. sess, err := mgr.CreateSession(state.DisplayScreenName("advbot"), []string{"presence"}, inst, "", slog.Default())
  130. require.NoError(t, err)
  131. sess.FeedbagLoader = emptyFeedbagLoader
  132. // Healthy session resolves.
  133. got, err := mgr.GetSession(context.Background(), sess.AimSID)
  134. require.NoError(t, err)
  135. assert.Same(t, sess, got)
  136. // Burst until EvaluateRateLimit escalates to disconnect, which closes the
  137. // account's OSCAR session.
  138. var status wire.RateLimitStatus
  139. now := time.Now()
  140. for range 10 {
  141. if status = inst.Session().EvaluateRateLimit(now, 1); status == wire.RateLimitStatusDisconnect {
  142. break
  143. }
  144. }
  145. require.Equal(t, wire.RateLimitStatusDisconnect, status)
  146. require.True(t, inst.IsClosed(), "disconnect must close the OSCAR instance")
  147. // The aimsid no longer resolves, even though ExpiresAt is far in the future.
  148. _, err = mgr.GetSession(context.Background(), sess.AimSID)
  149. assert.ErrorIs(t, err, ErrWebAPISessionExpired)
  150. assert.False(t, sess.IsExpired(), "the guard must fire on OSCAR close, not on time expiry")
  151. // The reaper frees the dead entry on its next sweep.
  152. mgr.reapExpired()
  153. assert.NotContains(t, mgr.sessions, sess.AimSID)
  154. }
  155. // TestSessionManager_ShutdownDrainsAndClosesSessions verifies that Shutdown
  156. // collects every live session and tears it down: it drains the maps and closes
  157. // each session's event queue and OSCAR instance.
  158. func TestSessionManager_ShutdownDrainsAndClosesSessions(t *testing.T) {
  159. mgr := NewSessionManager()
  160. ctx := context.Background()
  161. inst1 := state.NewSession().AddInstance()
  162. inst2 := state.NewSession().AddInstance()
  163. s1, err := mgr.CreateSession(state.DisplayScreenName("alice"), []string{"presence"}, inst1, "", slog.Default())
  164. assert.NoError(t, err)
  165. s1.FeedbagLoader = emptyFeedbagLoader
  166. s2, err := mgr.CreateSession(state.DisplayScreenName("bob"), []string{"presence"}, inst2, "", slog.Default())
  167. assert.NoError(t, err)
  168. s2.FeedbagLoader = emptyFeedbagLoader
  169. assert.NoError(t, mgr.Shutdown(context.Background()))
  170. // Maps drained: the collect loop ran over both sessions.
  171. assert.Empty(t, mgr.sessions)
  172. // Each session's event queue and OSCAR instance were closed: the teardown
  173. // loop ran for every collected session.
  174. for _, s := range []*Session{s1, s2} {
  175. assertQueueClosed(t, ctx, s)
  176. }
  177. for _, inst := range []*state.SessionInstance{inst1, inst2} {
  178. select {
  179. case <-inst.Closed():
  180. default:
  181. t.Error("OSCAR instance should be closed")
  182. }
  183. }
  184. }
  185. // TestSessionManager_ReapExpired verifies reapExpired removes and tears
  186. // down only expired sessions, leaving live ones untouched.
  187. func TestSessionManager_ReapExpired(t *testing.T) {
  188. mgr := NewSessionManager()
  189. ctx := context.Background()
  190. expiredInst := state.NewSession().AddInstance()
  191. liveInst := state.NewSession().AddInstance()
  192. expired, err := mgr.CreateSession("alice", []string{"presence"}, expiredInst, "", slog.Default())
  193. assert.NoError(t, err)
  194. expired.FeedbagLoader = emptyFeedbagLoader
  195. live, err := mgr.CreateSession("bob", []string{"presence"}, liveInst, "", slog.Default())
  196. assert.NoError(t, err)
  197. live.FeedbagLoader = emptyFeedbagLoader
  198. // Force alice's session into the past; bob keeps its default future expiry.
  199. expired.ExpiresAt = time.Now().Add(-time.Minute)
  200. mgr.reapExpired()
  201. // Expired session removed; live session retained.
  202. assert.NotContains(t, mgr.sessions, expired.AimSID)
  203. assert.Contains(t, mgr.sessions, live.AimSID)
  204. // Expired session torn down: event queue and OSCAR instance closed.
  205. assertQueueClosed(t, ctx, expired)
  206. select {
  207. case <-expiredInst.Closed():
  208. default:
  209. t.Error("expired session's OSCAR instance should be closed")
  210. }
  211. // Live session left running.
  212. select {
  213. case <-liveInst.Closed():
  214. t.Error("live session's OSCAR instance should not be closed")
  215. default:
  216. }
  217. }
  218. // assertQueueClosed asserts the session's event queue is closed: a fetch returns
  219. // straight away with no events and no error, rather than parking for the timeout.
  220. func assertQueueClosed(t *testing.T, ctx context.Context, sess *Session) {
  221. t.Helper()
  222. const timeout = 5 * time.Second
  223. start := time.Now()
  224. events, err := sess.EventQueue.Fetch(ctx, 0, timeout)
  225. assert.NoError(t, err)
  226. assert.Empty(t, events)
  227. assert.Less(t, time.Since(start), timeout/2, "fetch parked instead of returning on a closed queue")
  228. }
  229. // TestSessionManager_ShutdownWithoutReaper verifies Shutdown returns when no
  230. // reaper was ever started. Shutdown must not depend on the caller cancelling the
  231. // context passed to Run.
  232. func TestSessionManager_ShutdownWithoutReaper(t *testing.T) {
  233. mgr := NewSessionManager()
  234. done := make(chan struct{})
  235. go func() {
  236. defer close(done)
  237. // This test is about Shutdown returning at all, not what it returns.
  238. _ = mgr.Shutdown(context.Background())
  239. }()
  240. select {
  241. case <-done:
  242. case <-time.After(5 * time.Second):
  243. t.Fatal("Shutdown hung waiting for a reaper that was never started")
  244. }
  245. }
  246. // TestSessionManager_ShutdownJoinsReaper verifies Shutdown stops a running
  247. // reaper on its own and does not return until that reaper has exited.
  248. func TestSessionManager_ShutdownJoinsReaper(t *testing.T) {
  249. mgr := NewSessionManager()
  250. reaperExited := make(chan struct{})
  251. go func() {
  252. defer close(reaperExited)
  253. mgr.Run(context.Background()) // context is never cancelled: Shutdown must stop it
  254. }()
  255. // Give Run a chance to register itself before shutting down.
  256. time.Sleep(50 * time.Millisecond)
  257. done := make(chan struct{})
  258. go func() {
  259. defer close(done)
  260. // This test is about Shutdown returning at all, not what it returns.
  261. _ = mgr.Shutdown(context.Background())
  262. }()
  263. select {
  264. case <-done:
  265. case <-time.After(5 * time.Second):
  266. t.Fatal("Shutdown hung instead of stopping the reaper")
  267. }
  268. // Shutdown joins the reaper, so it has already exited by the time it returns.
  269. select {
  270. case <-reaperExited:
  271. default:
  272. t.Error("Shutdown returned before the reaper exited")
  273. }
  274. }
  275. // TestSessionManager_RunAfterShutdown verifies a reaper that loses the race
  276. // with Shutdown never starts, so it cannot reap an already-drained manager.
  277. func TestSessionManager_RunAfterShutdown(t *testing.T) {
  278. mgr := NewSessionManager()
  279. assert.NoError(t, mgr.Shutdown(context.Background()))
  280. done := make(chan struct{})
  281. go func() {
  282. defer close(done)
  283. mgr.Run(context.Background())
  284. }()
  285. select {
  286. case <-done:
  287. case <-time.After(5 * time.Second):
  288. t.Fatal("Run should be a no-op on a closed manager")
  289. }
  290. }
  291. // The client deletes the alias it holds each time it merges a user map, so every
  292. // event naming a buddy has to repeat it. An incoming IM and a presence change both
  293. // carry a user map, and both would otherwise rename an aliased buddy.
  294. func TestSession_UINBuddyReportsICQOnArrivalAndDeparture(t *testing.T) {
  295. sess := &Session{
  296. ScreenName: state.DisplayScreenName("me"),
  297. Events: []string{"presence"},
  298. EventQueue: NewEventQueue(10),
  299. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  300. FeedbagLoader: emptyFeedbagLoader,
  301. }
  302. sess.handleBuddyArrived(wire.SNACMessage{Body: wire.SNAC_0x03_0x0B_BuddyArrived{
  303. TLVUserInfo: wire.TLVUserInfo{ScreenName: "100003"},
  304. }})
  305. sess.handleBuddyDeparted(wire.SNACMessage{Body: wire.SNAC_0x03_0x0C_BuddyDeparted{
  306. TLVUserInfo: wire.TLVUserInfo{ScreenName: "100003"},
  307. }})
  308. events := sess.EventQueue.GetAllEvents()
  309. require.Len(t, events, 2)
  310. assert.Equal(t, "icq", events[0].Data.(PresenceEvent).UserType)
  311. assert.Equal(t, "icq", events[1].Data.(PresenceEvent).UserType)
  312. }
  313. func TestSession_RepeatsBuddyAliasOnOSCAREvents(t *testing.T) {
  314. newSession := func() *Session {
  315. return &Session{
  316. ScreenName: state.DisplayScreenName("me"),
  317. Events: []string{"im", "conversation", "presence"},
  318. EventQueue: NewEventQueue(10),
  319. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  320. FeedbagLoader: aliasFeedbagLoader(map[string]string{"mikekelly": "MICHAELKELLY"}),
  321. }
  322. }
  323. t.Run("incoming IM", func(t *testing.T) {
  324. sess := newSession()
  325. frags, err := wire.ICBMFragmentList("hello")
  326. require.NoError(t, err)
  327. body := wire.SNAC_0x04_0x07_ICBMChannelMsgToClient{
  328. ChannelID: wire.ICBMChannelIM,
  329. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  330. }
  331. body.Append(wire.NewTLVBE(wire.ICBMTLVAOLIMData, frags))
  332. sess.handleIncomingIM(wire.SNACMessage{Body: body})
  333. events := sess.EventQueue.GetAllEvents()
  334. require.NotEmpty(t, events)
  335. imEvent := events[0].Data.(IMEvent)
  336. assert.Equal(t, "mikekelly", imEvent.Source.AimID)
  337. assert.Equal(t, "Mike Kelly", imEvent.Source.DisplayID)
  338. assert.Equal(t, "MICHAELKELLY", imEvent.Source.Friendly)
  339. })
  340. t.Run("buddy arrived", func(t *testing.T) {
  341. sess := newSession()
  342. sess.handleBuddyArrived(wire.SNACMessage{Body: wire.SNAC_0x03_0x0B_BuddyArrived{
  343. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  344. }})
  345. events := sess.EventQueue.GetAllEvents()
  346. require.Len(t, events, 1)
  347. presence := events[0].Data.(PresenceEvent)
  348. assert.Equal(t, "mikekelly", presence.AimID)
  349. assert.Equal(t, "MICHAELKELLY", presence.Friendly)
  350. })
  351. t.Run("buddy departed", func(t *testing.T) {
  352. sess := newSession()
  353. sess.handleBuddyDeparted(wire.SNACMessage{Body: wire.SNAC_0x03_0x0C_BuddyDeparted{
  354. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  355. }})
  356. events := sess.EventQueue.GetAllEvents()
  357. require.Len(t, events, 1)
  358. presence := events[0].Data.(PresenceEvent)
  359. assert.Equal(t, "mikekelly", presence.AimID)
  360. assert.Equal(t, "MICHAELKELLY", presence.Friendly)
  361. })
  362. t.Run("unaliased buddy omits friendly", func(t *testing.T) {
  363. sess := newSession()
  364. sess.handleBuddyArrived(wire.SNACMessage{Body: wire.SNAC_0x03_0x0B_BuddyArrived{
  365. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Someone Else"},
  366. }})
  367. events := sess.EventQueue.GetAllEvents()
  368. require.Len(t, events, 1)
  369. assert.Empty(t, events[0].Data.(PresenceEvent).Friendly)
  370. })
  371. }
  372. // Aliases all come from one feedbag query, so a signon that brings a whole buddy
  373. // list online must not re-query the feedbag per buddy.
  374. func TestSession_CachesBuddyAliases(t *testing.T) {
  375. var loads int
  376. sess := &Session{
  377. ScreenName: state.DisplayScreenName("me"),
  378. Events: []string{"presence"},
  379. EventQueue: NewEventQueue(10),
  380. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  381. FeedbagLoader: func(context.Context) ([]wire.FeedbagItem, error) {
  382. loads++
  383. return aliasFeedbagItems(map[string]string{"mikekelly": "MICHAELKELLY"}), nil
  384. },
  385. }
  386. for range 5 {
  387. sess.handleBuddyArrived(wire.SNACMessage{Body: wire.SNAC_0x03_0x0B_BuddyArrived{
  388. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  389. }})
  390. }
  391. events := sess.EventQueue.GetAllEvents()
  392. require.Len(t, events, 5)
  393. for _, event := range events {
  394. assert.Equal(t, "MICHAELKELLY", event.Data.(PresenceEvent).Friendly)
  395. }
  396. assert.Equal(t, 1, loads, "aliases should be loaded once, not once per event")
  397. }
  398. // A feedbag change from another of the owner's clients arrives as a SNAC, which is
  399. // the session's only signal that its cached aliases are stale.
  400. func TestSession_FeedbagSNACInvalidatesAliasCache(t *testing.T) {
  401. alias := "MICHAELKELLY"
  402. sess := &Session{
  403. ScreenName: state.DisplayScreenName("me"),
  404. Events: []string{"presence"},
  405. EventQueue: NewEventQueue(10),
  406. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  407. FeedbagLoader: func(context.Context) ([]wire.FeedbagItem, error) {
  408. return aliasFeedbagItems(map[string]string{"mikekelly": alias}), nil
  409. },
  410. }
  411. arrive := func() PresenceEvent {
  412. sess.handleBuddyArrived(wire.SNACMessage{Body: wire.SNAC_0x03_0x0B_BuddyArrived{
  413. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  414. }})
  415. events := sess.EventQueue.GetAllEvents()
  416. require.NotEmpty(t, events)
  417. return events[len(events)-1].Data.(PresenceEvent)
  418. }
  419. assert.Equal(t, "MICHAELKELLY", arrive().Friendly)
  420. // The buddy is renamed elsewhere: the feedbag SNAC must drop the cached map.
  421. alias = "MIKE"
  422. sess.handleFeedbagMessage(wire.SNACMessage{
  423. Frame: wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagUpdateItem},
  424. Body: wire.SNAC_0x13_0x09_FeedbagUpdateItem{},
  425. })
  426. assert.Equal(t, "MIKE", arrive().Friendly)
  427. }
  428. // Permit/deny changes from another of the owner's clients arrive as an insert,
  429. // an update, or a delete, and all three have to refresh the client's privacy
  430. // state.
  431. func TestSession_FeedbagSNACRefreshesPermitDeny(t *testing.T) {
  432. denyItem := wire.FeedbagItem{ClassID: wire.FeedbagClassIDDeny, Name: "blockeduser"}
  433. buddyItem := wire.FeedbagItem{ClassID: wire.FeedbagClassIdBuddy, Name: "friend"}
  434. tests := []struct {
  435. name string
  436. subGroup uint16
  437. body any
  438. wantEvent bool
  439. }{
  440. {
  441. name: "insert relays an update body",
  442. subGroup: wire.FeedbagInsertItem,
  443. body: wire.SNAC_0x13_0x09_FeedbagUpdateItem{Items: []wire.FeedbagItem{denyItem}},
  444. wantEvent: true,
  445. },
  446. {
  447. name: "update",
  448. subGroup: wire.FeedbagUpdateItem,
  449. body: wire.SNAC_0x13_0x09_FeedbagUpdateItem{Items: []wire.FeedbagItem{denyItem}},
  450. wantEvent: true,
  451. },
  452. {
  453. name: "delete",
  454. subGroup: wire.FeedbagDeleteItem,
  455. body: wire.SNAC_0x13_0x0A_FeedbagDeleteItem{Items: []wire.FeedbagItem{denyItem}},
  456. wantEvent: true,
  457. },
  458. {
  459. name: "buddy item only",
  460. subGroup: wire.FeedbagInsertItem,
  461. body: wire.SNAC_0x13_0x09_FeedbagUpdateItem{Items: []wire.FeedbagItem{buddyItem}},
  462. wantEvent: false,
  463. },
  464. }
  465. for _, tt := range tests {
  466. t.Run(tt.name, func(t *testing.T) {
  467. sess := &Session{
  468. ScreenName: state.DisplayScreenName("me"),
  469. EventQueue: NewEventQueue(10),
  470. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  471. PermitDenyRefresher: func(_ context.Context) (any, error) {
  472. return map[string]any{"pdMode": "denySome"}, nil
  473. },
  474. FeedbagLoader: emptyFeedbagLoader,
  475. }
  476. sess.handleFeedbagMessage(wire.SNACMessage{
  477. Frame: wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: tt.subGroup},
  478. Body: tt.body,
  479. })
  480. var got int
  481. for _, event := range sess.EventQueue.GetAllEvents() {
  482. if event.Type == EventTypePermitDeny {
  483. got++
  484. }
  485. }
  486. if tt.wantEvent {
  487. assert.Equal(t, 1, got)
  488. } else {
  489. assert.Zero(t, got)
  490. }
  491. })
  492. }
  493. }
  494. // A session sees no SNAC for feedbag writes it makes itself, so the handlers that
  495. // perform those writes invalidate the cache directly.
  496. func TestSession_InvalidateFeedbag(t *testing.T) {
  497. alias := "MICHAELKELLY"
  498. sess := &Session{
  499. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  500. FeedbagLoader: func(context.Context) ([]wire.FeedbagItem, error) {
  501. return aliasFeedbagItems(map[string]string{"mikekelly": alias}), nil
  502. },
  503. }
  504. assert.Equal(t, "MICHAELKELLY", sess.Aliases(context.Background())["mikekelly"])
  505. alias = "MIKE"
  506. assert.Equal(t, "MICHAELKELLY", sess.Aliases(context.Background())["mikekelly"], "cached until invalidated")
  507. sess.InvalidateFeedbag()
  508. assert.Equal(t, "MIKE", sess.Aliases(context.Background())["mikekelly"])
  509. }
  510. // A failed load must not be cached as an empty map: aliases would stay missing for
  511. // the life of the session.
  512. func TestSession_FeedbagLoadErrorIsNotCached(t *testing.T) {
  513. var loads int
  514. sess := &Session{
  515. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  516. FeedbagLoader: func(context.Context) ([]wire.FeedbagItem, error) {
  517. loads++
  518. if loads == 1 {
  519. return nil, io.EOF
  520. }
  521. return aliasFeedbagItems(map[string]string{"mikekelly": "MICHAELKELLY"}), nil
  522. },
  523. }
  524. assert.Empty(t, sess.Aliases(context.Background()))
  525. assert.Equal(t, "MICHAELKELLY", sess.Aliases(context.Background())["mikekelly"])
  526. }
  527. func TestSession_HandleIncomingIM_NormalizesAimID(t *testing.T) {
  528. sess := &Session{
  529. ScreenName: state.DisplayScreenName("me"),
  530. Events: []string{"im", "conversation"},
  531. EventQueue: NewEventQueue(10),
  532. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  533. FeedbagLoader: emptyFeedbagLoader,
  534. }
  535. frags, err := wire.ICBMFragmentList("hello")
  536. assert.NoError(t, err)
  537. body := wire.SNAC_0x04_0x07_ICBMChannelMsgToClient{
  538. ChannelID: wire.ICBMChannelIM,
  539. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  540. }
  541. body.Append(wire.NewTLVBE(wire.ICBMTLVAOLIMData, frags))
  542. sess.handleIncomingIM(wire.SNACMessage{Body: body})
  543. events := sess.EventQueue.GetAllEvents()
  544. require.Len(t, events, 2)
  545. imEvent := events[0].Data.(IMEvent)
  546. assert.Equal(t, "mikekelly", imEvent.Source.AimID)
  547. assert.Equal(t, "Mike Kelly", imEvent.Source.DisplayID)
  548. convData := events[1].Data.(*ConversationData)
  549. require.Len(t, convData.Conversations, 1)
  550. entry := convData.Conversations[0]
  551. assert.Equal(t, "mikekelly", entry.AimID)
  552. assert.Equal(t, "Mike Kelly", entry.DisplayID)
  553. require.NotNil(t, entry.LastIM)
  554. assert.Equal(t, "mikekelly", entry.LastIM.Sender)
  555. // The IM log is keyed by aimId, so the conversation the client opens from
  556. // this event finds its own history.
  557. msgs := sess.GetStoredIMs(StoredIMQuery{PartnerAimID: "mikekelly", NToGet: 10})
  558. require.Len(t, msgs, 1)
  559. assert.Equal(t, "hello", msgs[0].Message)
  560. }
  561. func TestSession_HandleTypingNotification_NormalizesAimID(t *testing.T) {
  562. sess := &Session{
  563. Events: []string{"typing"},
  564. EventQueue: NewEventQueue(10),
  565. FeedbagLoader: emptyFeedbagLoader,
  566. }
  567. sess.handleTypingNotification(wire.SNACMessage{
  568. Body: wire.SNAC_0x04_0x14_ICBMClientEvent{
  569. ScreenName: "Mike Kelly",
  570. Event: 0x0002,
  571. },
  572. })
  573. events := sess.EventQueue.GetAllEvents()
  574. require.Len(t, events, 1)
  575. typing := events[0].Data.(TypingEvent)
  576. assert.Equal(t, "mikekelly", typing.AimID)
  577. assert.Equal(t, "typing", typing.TypingStatus)
  578. }
  579. func TestSession_HandleBuddyArrivedDeparted_NormalizesAimID(t *testing.T) {
  580. sess := &Session{
  581. Events: []string{"presence"},
  582. EventQueue: NewEventQueue(10),
  583. FeedbagLoader: emptyFeedbagLoader,
  584. }
  585. sess.handleBuddyArrived(wire.SNACMessage{
  586. Body: wire.SNAC_0x03_0x0B_BuddyArrived{
  587. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  588. },
  589. })
  590. sess.handleBuddyDeparted(wire.SNACMessage{
  591. Body: wire.SNAC_0x03_0x0C_BuddyDeparted{
  592. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  593. },
  594. })
  595. events := sess.EventQueue.GetAllEvents()
  596. require.Len(t, events, 2)
  597. arrived := events[0].Data.(PresenceEvent)
  598. assert.Equal(t, "mikekelly", arrived.AimID)
  599. assert.Equal(t, "online", arrived.State)
  600. departed := events[1].Data.(PresenceEvent)
  601. assert.Equal(t, "mikekelly", departed.AimID)
  602. assert.Equal(t, "offline", departed.State)
  603. }
  604. // A BuddyArrived carries the buddy's current icon as TLV 0x1D, so an icon change
  605. // rides along on the presence broadcast and must reach the presence event. The
  606. // stub BuddyIconURL stands in for the handlers-side URL formatter, which state
  607. // cannot import.
  608. var testIconBART = wire.BARTID{
  609. Type: wire.BARTTypesBuddyIcon,
  610. BARTInfo: wire.BARTInfo{Hash: []byte{0xde, 0xad, 0xbe, 0xef}},
  611. }
  612. var testStatusBART = statusBARTID("brb")
  613. // statusBARTID builds the BART item that advertises statusMsg as a user's status
  614. // message. It panics only on a message too long to fit the item.
  615. func statusBARTID(statusMsg string) wire.BARTID {
  616. var id wire.BARTID
  617. if err := id.SetStatusText(statusMsg); err != nil {
  618. panic(err)
  619. }
  620. return id
  621. }
  622. func TestSession_PublishesBuddyIconOnPresence(t *testing.T) {
  623. newSession := func() *Session {
  624. return &Session{
  625. ScreenName: state.DisplayScreenName("me"),
  626. Events: []string{"presence"},
  627. EventQueue: NewEventQueue(10),
  628. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  629. BuddyIconURL: func(sn state.IdentScreenName, hash []byte) string {
  630. if len(hash) == 0 {
  631. return "placeholder:" + sn.String()
  632. }
  633. return "icon:" + hex.EncodeToString(hash)
  634. },
  635. FeedbagLoader: emptyFeedbagLoader,
  636. }
  637. }
  638. arrived := func(sess *Session, screenName string, hash []byte) {
  639. info := wire.TLVUserInfo{ScreenName: screenName}
  640. if hash != nil {
  641. info.Append(wire.NewTLVBE(wire.OServiceUserInfoBARTInfo, wire.BARTID{
  642. Type: wire.BARTTypesBuddyIcon,
  643. BARTInfo: wire.BARTInfo{Hash: hash},
  644. }))
  645. }
  646. sess.handleBuddyArrived(wire.SNACMessage{Body: wire.SNAC_0x03_0x0B_BuddyArrived{TLVUserInfo: info}})
  647. }
  648. lastPresence := func(sess *Session) PresenceEvent {
  649. events := sess.EventQueue.GetAllEvents()
  650. require.Len(t, events, 1)
  651. return events[0].Data.(PresenceEvent)
  652. }
  653. t.Run("icon hash yields the content-addressed URL", func(t *testing.T) {
  654. sess := newSession()
  655. arrived(sess, "Mike Kelly", []byte{0xde, 0xad, 0xbe, 0xef})
  656. assert.Equal(t, "icon:deadbeef", lastPresence(sess).BuddyIcon)
  657. })
  658. t.Run("no icon TLV yields the placeholder URL", func(t *testing.T) {
  659. sess := newSession()
  660. arrived(sess, "Mike Kelly", nil)
  661. assert.Equal(t, "placeholder:mikekelly", lastPresence(sess).BuddyIcon)
  662. })
  663. // The BART TLV is a list, so a status message rides in it next to the icon.
  664. arrivedBART := func(sess *Session, screenName string, ids []wire.BARTID) {
  665. info := wire.TLVUserInfo{ScreenName: screenName}
  666. info.Append(wire.NewTLVBE(wire.OServiceUserInfoBARTInfo, ids))
  667. sess.handleBuddyArrived(wire.SNACMessage{Body: wire.SNAC_0x03_0x0B_BuddyArrived{TLVUserInfo: info}})
  668. }
  669. t.Run("a buddy's status message reaches the presence event", func(t *testing.T) {
  670. sess := newSession()
  671. arrivedBART(sess, "Mike Kelly", []wire.BARTID{testIconBART, testStatusBART})
  672. assert.Equal(t, "brb", lastPresence(sess).StatusMsg)
  673. })
  674. t.Run("no status message leaves the field empty", func(t *testing.T) {
  675. sess := newSession()
  676. arrivedBART(sess, "Mike Kelly", []wire.BARTID{testIconBART})
  677. assert.Empty(t, lastPresence(sess).StatusMsg)
  678. })
  679. t.Run("a status message next to the icon does not displace it", func(t *testing.T) {
  680. sess := newSession()
  681. arrivedBART(sess, "Mike Kelly", []wire.BARTID{testIconBART, testStatusBART})
  682. assert.Equal(t, "icon:deadbeef", lastPresence(sess).BuddyIcon)
  683. })
  684. t.Run("a status message without an icon yields the placeholder URL", func(t *testing.T) {
  685. sess := newSession()
  686. arrivedBART(sess, "Mike Kelly", []wire.BARTID{testStatusBART})
  687. assert.Equal(t, "placeholder:mikekelly", lastPresence(sess).BuddyIcon)
  688. })
  689. t.Run("cleared icon yields a URL naming the sentinel hash", func(t *testing.T) {
  690. sess := newSession()
  691. arrived(sess, "Mike Kelly", wire.GetClearIconHash())
  692. assert.Equal(t, "icon:"+hex.EncodeToString(wire.GetClearIconHash()), lastPresence(sess).BuddyIcon)
  693. })
  694. t.Run("departed omits the icon so the client preserves it", func(t *testing.T) {
  695. sess := newSession()
  696. sess.handleBuddyDeparted(wire.SNACMessage{Body: wire.SNAC_0x03_0x0C_BuddyDeparted{
  697. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  698. }})
  699. assert.Empty(t, lastPresence(sess).BuddyIcon)
  700. })
  701. t.Run("no callback wired omits the icon", func(t *testing.T) {
  702. sess := newSession()
  703. sess.BuddyIconURL = nil
  704. arrived(sess, "Mike Kelly", []byte{0x01})
  705. assert.Empty(t, lastPresence(sess).BuddyIcon)
  706. })
  707. }
  708. // A change to a user's own info is relayed to their session as
  709. // OServiceUserInfoUpdate, which the pump turns into a myInfo event so the
  710. // identity badge re-renders.
  711. func TestSession_PushesMyInfoOnUserInfoUpdate(t *testing.T) {
  712. newSession := func(events ...string) *Session {
  713. return &Session{
  714. ScreenName: state.DisplayScreenName("me"),
  715. OSCARSession: state.NewSession().AddInstance(),
  716. BaseURL: "http://api.example.com",
  717. Events: events,
  718. EventQueue: NewEventQueue(10),
  719. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  720. BuddyIconURL: func(sn state.IdentScreenName, hash []byte) string {
  721. if len(hash) == 0 {
  722. return "placeholder:" + sn.String()
  723. }
  724. return "icon:" + hex.EncodeToString(hash)
  725. },
  726. FeedbagLoader: emptyFeedbagLoader,
  727. }
  728. }
  729. update := func(info wire.TLVUserInfo) wire.SNACMessage {
  730. return wire.SNACMessage{
  731. Frame: wire.SNACFrame{
  732. FoodGroup: wire.OService,
  733. SubGroup: wire.OServiceUserInfoUpdate,
  734. },
  735. Body: wire.SNAC_0x01_0x0F_OServiceUserInfoUpdate{
  736. UserInfo: []wire.TLVUserInfo{info},
  737. },
  738. }
  739. }
  740. lastMyInfo := func(t *testing.T, sess *Session) *MyInfo {
  741. t.Helper()
  742. events := sess.EventQueue.GetAllEvents()
  743. require.Len(t, events, 1)
  744. require.Equal(t, EventTypeMyInfo, events[0].Type)
  745. return events[0].Data.(*MyInfo)
  746. }
  747. t.Run("subscribed session gets one myInfo built from the SNAC", func(t *testing.T) {
  748. sess := newSession("myInfo")
  749. sess.handleSNACMessage(update(wire.TLVUserInfo{ScreenName: "Mike Kelly"}))
  750. myInfo := lastMyInfo(t, sess)
  751. assert.Equal(t, "mikekelly", myInfo.AimID)
  752. assert.Equal(t, "Mike Kelly", myInfo.DisplayID)
  753. assert.Equal(t, "Mike Kelly", myInfo.Friendly)
  754. assert.Equal(t, "online", myInfo.State)
  755. })
  756. t.Run("a presence subscription also delivers myInfo", func(t *testing.T) {
  757. sess := newSession("presence")
  758. sess.handleSNACMessage(update(wire.TLVUserInfo{ScreenName: "me"}))
  759. assert.Len(t, sess.EventQueue.GetAllEvents(), 1)
  760. })
  761. t.Run("unsubscribed session gets nothing", func(t *testing.T) {
  762. sess := newSession("im")
  763. sess.handleSNACMessage(update(wire.TLVUserInfo{ScreenName: "me"}))
  764. assert.Empty(t, sess.EventQueue.GetAllEvents())
  765. })
  766. t.Run("other OService subgroups are ignored", func(t *testing.T) {
  767. sess := newSession("myInfo")
  768. sess.handleSNACMessage(wire.SNACMessage{Frame: wire.SNACFrame{
  769. FoodGroup: wire.OService,
  770. SubGroup: wire.OServiceRateParamsQuery,
  771. }})
  772. assert.Empty(t, sess.EventQueue.GetAllEvents())
  773. })
  774. t.Run("an update carrying no user info block pushes nothing", func(t *testing.T) {
  775. sess := newSession("myInfo")
  776. sess.handleSNACMessage(wire.SNACMessage{
  777. Frame: wire.SNACFrame{
  778. FoodGroup: wire.OService,
  779. SubGroup: wire.OServiceUserInfoUpdate,
  780. },
  781. Body: wire.SNAC_0x01_0x0F_OServiceUserInfoUpdate{},
  782. })
  783. assert.Empty(t, sess.EventQueue.GetAllEvents())
  784. })
  785. t.Run("the away message comes from the session", func(t *testing.T) {
  786. sess := newSession("myInfo")
  787. // Session.AwayMessage reads only instances that are actually away.
  788. sess.OSCARSession.SetUserInfoFlag(wire.OServiceUserFlagUnavailable)
  789. sess.OSCARSession.SetAwayMessage("brb")
  790. info := wire.TLVUserInfo{ScreenName: "me"}
  791. info.Append(wire.NewTLVBE(wire.OServiceUserInfoUserFlags, wire.OServiceUserFlagUnavailable))
  792. sess.handleSNACMessage(update(info))
  793. myInfo := lastMyInfo(t, sess)
  794. assert.Equal(t, "away", myInfo.State)
  795. assert.Equal(t, "brb", myInfo.AwayMsg)
  796. })
  797. t.Run("a mood capability publishes its icon", func(t *testing.T) {
  798. sess := newSession("myInfo")
  799. info := wire.TLVUserInfo{ScreenName: "me"}
  800. info.Append(wire.NewTLVBE(wire.OServiceUserInfoOscarCaps, wire.CapXStatusPlate[:]))
  801. sess.handleSNACMessage(update(info))
  802. assert.Equal(t, "http://api.example.com/mood?id="+wire.MoodIconID("0icqmood6"), lastMyInfo(t, sess).MoodIcon)
  803. })
  804. t.Run("the icon hash yields the content-addressed URL", func(t *testing.T) {
  805. sess := newSession("myInfo")
  806. info := wire.TLVUserInfo{ScreenName: "me"}
  807. info.Append(wire.NewTLVBE(wire.OServiceUserInfoBARTInfo, wire.BARTID{
  808. Type: wire.BARTTypesBuddyIcon,
  809. BARTInfo: wire.BARTInfo{Hash: []byte{0xde, 0xad, 0xbe, 0xef}},
  810. }))
  811. sess.handleSNACMessage(update(info))
  812. assert.Equal(t, "icon:deadbeef", lastMyInfo(t, sess).BuddyIcon)
  813. })
  814. t.Run("a status message without an icon yields the placeholder URL", func(t *testing.T) {
  815. sess := newSession("myInfo")
  816. info := wire.TLVUserInfo{ScreenName: "me"}
  817. info.Append(wire.NewTLVBE(wire.OServiceUserInfoBARTInfo, []wire.BARTID{testStatusBART}))
  818. sess.handleSNACMessage(update(info))
  819. assert.Equal(t, "placeholder:me", lastMyInfo(t, sess).BuddyIcon)
  820. })
  821. // The user info update is the only myInfo raised after a status message is set,
  822. // so dropping the text here erases it from the user's own badge.
  823. t.Run("the user's own status message survives the update", func(t *testing.T) {
  824. sess := newSession("myInfo")
  825. info := wire.TLVUserInfo{ScreenName: "me"}
  826. info.Append(wire.NewTLVBE(wire.OServiceUserInfoBARTInfo, []wire.BARTID{testStatusBART}))
  827. sess.handleSNACMessage(update(info))
  828. assert.Equal(t, "brb", lastMyInfo(t, sess).StatusMsg)
  829. })
  830. t.Run("no status message leaves the field empty", func(t *testing.T) {
  831. sess := newSession("myInfo")
  832. sess.handleSNACMessage(update(wire.TLVUserInfo{ScreenName: "me"}))
  833. assert.Empty(t, lastMyInfo(t, sess).StatusMsg)
  834. })
  835. t.Run("no icon TLV yields the placeholder URL, which clears a removed icon", func(t *testing.T) {
  836. sess := newSession("myInfo")
  837. sess.handleSNACMessage(update(wire.TLVUserInfo{ScreenName: "me"}))
  838. assert.Equal(t, "placeholder:me", lastMyInfo(t, sess).BuddyIcon)
  839. })
  840. t.Run("the state is read off the user info block", func(t *testing.T) {
  841. tests := []struct {
  842. name string
  843. screenName string
  844. flags uint16
  845. status uint32
  846. idle uint16
  847. want string
  848. }{
  849. {name: "invisible", screenName: "me", status: wire.OServiceUserStatusInvisible, want: "invisible"},
  850. {name: "icq busy", screenName: "100003", status: wire.OServiceUserStatusBusy, want: "occupied"},
  851. {name: "aim busy reports away", screenName: "me", status: wire.OServiceUserStatusBusy, want: "away"},
  852. {name: "icq dnd", screenName: "100003", status: wire.OServiceUserStatusDND, want: "dnd"},
  853. {name: "away flag", screenName: "me", flags: wire.OServiceUserFlagUnavailable, want: "away"},
  854. {name: "away status bit", screenName: "me", status: wire.OServiceUserStatusAway, want: "away"},
  855. {name: "idle", screenName: "me", idle: 5, want: "idle"},
  856. {name: "nothing set", screenName: "me", want: "online"},
  857. }
  858. for _, tt := range tests {
  859. t.Run(tt.name, func(t *testing.T) {
  860. sess := newSession("myInfo")
  861. info := wire.TLVUserInfo{ScreenName: tt.screenName}
  862. info.Append(wire.NewTLVBE(wire.OServiceUserInfoUserFlags, tt.flags))
  863. info.Append(wire.NewTLVBE(wire.OServiceUserInfoStatus, tt.status))
  864. if tt.idle > 0 {
  865. info.Append(wire.NewTLVBE(wire.OServiceUserInfoIdleTime, tt.idle))
  866. }
  867. sess.handleSNACMessage(update(info))
  868. assert.Equal(t, tt.want, lastMyInfo(t, sess).State)
  869. })
  870. }
  871. })
  872. }
  873. // TestSessionManager_ShutdownBoundedByContext verifies that Shutdown
  874. // honors its context instead of blocking indefinitely. A listener goroutine that
  875. // ignores cancellation must not be able to hold the whole server open: main
  876. // budgets a few seconds for every server's shutdown combined, so an unbounded
  877. // wait here means the process never exits.
  878. func TestSessionManager_ShutdownBoundedByContext(t *testing.T) {
  879. mgr := NewSessionManager()
  880. inst := state.NewSession().AddInstance()
  881. sess, err := mgr.CreateSession("alice", []string{"presence"}, inst, "", slog.Default())
  882. assert.NoError(t, err)
  883. sess.FeedbagLoader = emptyFeedbagLoader
  884. // Stand in for a listener wedged somewhere that never observes cancellation.
  885. release := make(chan struct{})
  886. defer close(release)
  887. sess.listeners.Go(func() {
  888. <-release
  889. })
  890. ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
  891. defer cancel()
  892. start := time.Now()
  893. err = mgr.Shutdown(ctx)
  894. elapsed := time.Since(start)
  895. assert.ErrorIs(t, err, context.DeadlineExceeded)
  896. assert.Less(t, elapsed, 2*time.Second, "Shutdown must give up at its deadline, not wait on the stuck listener")
  897. }
  898. // TestSession_CloseCancelsSessionContext verifies that Close cancels the
  899. // context handed to the refresher callbacks. The listener runs feedbag queries
  900. // through it, and without cancellation Close's wait lasts as long as the query.
  901. func TestSession_CloseCancelsSessionContext(t *testing.T) {
  902. mgr := NewSessionManager()
  903. inst := state.NewSession().AddInstance()
  904. sess, err := mgr.CreateSession("alice", []string{"presence"}, inst, "", slog.Default())
  905. assert.NoError(t, err)
  906. sess.FeedbagLoader = emptyFeedbagLoader
  907. assert.NoError(t, sess.ctx.Err(), "session context should be live before Close")
  908. sess.Close()
  909. assert.ErrorIs(t, sess.ctx.Err(), context.Canceled)
  910. }
  911. // A message replayed out of the offline store arrives as an ordinary
  912. // ICBMChannelMsgToClient stamped with a send time. The client models that as its
  913. // own offlineIM event, keyed by a bare aimId and timestamped when the sender sent
  914. // it rather than when it was delivered.
  915. func TestSession_OfflineIM(t *testing.T) {
  916. sentAt := time.Now().Add(-2 * time.Hour).Unix()
  917. newSession := func(events ...string) *Session {
  918. return &Session{
  919. ScreenName: state.DisplayScreenName("me"),
  920. Events: events,
  921. EventQueue: NewEventQueue(10),
  922. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  923. FeedbagLoader: emptyFeedbagLoader,
  924. }
  925. }
  926. storedMsg := func(t *testing.T, withSendTime bool) wire.SNACMessage {
  927. t.Helper()
  928. frags, err := wire.ICBMFragmentList("sent while you were out")
  929. require.NoError(t, err)
  930. body := wire.SNAC_0x04_0x07_ICBMChannelMsgToClient{
  931. ChannelID: wire.ICBMChannelIM,
  932. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  933. }
  934. body.Append(wire.NewTLVBE(wire.ICBMTLVAOLIMData, frags))
  935. if withSendTime {
  936. body.Append(wire.NewTLVBE(wire.ICBMTLVSendTime, uint32(sentAt)))
  937. }
  938. return wire.SNACMessage{Body: body}
  939. }
  940. t.Run("send time yields an offlineIM event", func(t *testing.T) {
  941. sess := newSession("im", "offlineIM")
  942. sess.handleIncomingIM(storedMsg(t, true))
  943. events := sess.EventQueue.GetAllEvents()
  944. require.Len(t, events, 1)
  945. assert.Equal(t, EventTypeOfflineIM, events[0].Type)
  946. offline := events[0].Data.(OfflineIMEvent)
  947. assert.Equal(t, "mikekelly", offline.AimID)
  948. assert.Equal(t, "sent while you were out", offline.Message)
  949. assert.NotEmpty(t, offline.MsgID)
  950. assert.Equal(t, int64(sentAt), offline.Timestamp)
  951. })
  952. t.Run("no send time yields an im event", func(t *testing.T) {
  953. sess := newSession("im", "offlineIM")
  954. sess.handleIncomingIM(storedMsg(t, false))
  955. events := sess.EventQueue.GetAllEvents()
  956. require.Len(t, events, 1)
  957. assert.Equal(t, EventTypeIM, events[0].Type)
  958. })
  959. t.Run("offlineIM subscriber gets a conversation update", func(t *testing.T) {
  960. sess := newSession("offlineIM", "conversation")
  961. sess.handleIncomingIM(storedMsg(t, true))
  962. events := sess.EventQueue.GetAllEvents()
  963. require.Len(t, events, 2)
  964. assert.Equal(t, EventTypeOfflineIM, events[0].Type)
  965. assert.Equal(t, EventTypeConversation, events[1].Type)
  966. })
  967. // The history the client pulls with fetchStoredIMs has to order the message by
  968. // when it was sent, not when the session that drained the store started.
  969. t.Run("logs the message under its send time", func(t *testing.T) {
  970. sess := newSession("offlineIM")
  971. sess.handleIncomingIM(storedMsg(t, true))
  972. stored := sess.GetStoredIMs(StoredIMQuery{PartnerAimID: "mikekelly", NToGet: 10})
  973. require.Len(t, stored, 1)
  974. assert.Equal(t, int64(sentAt), stored[0].Date)
  975. })
  976. // Only a live IM is filtered on subscription here. Retrieval answers the
  977. // instance that asked and StartSession asks only for an offlineIM subscriber,
  978. // so a stamped message reaching a session that did not subscribe is not a state
  979. // this handler can be put in.
  980. t.Run("no subscription drops a live message", func(t *testing.T) {
  981. sess := newSession("presence")
  982. sess.handleIncomingIM(storedMsg(t, false))
  983. assert.Empty(t, sess.EventQueue.GetAllEvents())
  984. })
  985. }
  986. // A boot closes the account's OSCAR session out from under its web session. The
  987. // client is parked on a long poll at that moment, so it must be released with a
  988. // sessionEnded event rather than left to hang until the reaper's next sweep —
  989. // which measured 26-28s against a running server.
  990. func TestSession_BootReleasesParkedFetcherWithSessionEnded(t *testing.T) {
  991. mgr := NewSessionManager()
  992. inst := state.NewSession().AddInstance()
  993. sess, err := mgr.CreateSession(state.DisplayScreenName("mike"), []string{"presence"}, inst, "", slog.Default())
  994. require.NoError(t, err)
  995. sess.FeedbagLoader = emptyFeedbagLoader
  996. sess.StartListeningToOSCARSession()
  997. // Park a fetcher the way fetchEvents does, with nothing pending.
  998. type result struct {
  999. events []Event
  1000. err error
  1001. }
  1002. done := make(chan result, 1)
  1003. go func() {
  1004. events, err := sess.EventQueue.Fetch(context.Background(), 0, 60*time.Second)
  1005. done <- result{events, err}
  1006. }()
  1007. // Let the fetcher block before the session is taken away.
  1008. time.Sleep(50 * time.Millisecond)
  1009. inst.Session().CloseSession()
  1010. select {
  1011. case got := <-done:
  1012. require.NoError(t, got.err)
  1013. require.Len(t, got.events, 1)
  1014. assert.Equal(t, EventTypeSessionEnded, got.events[0].Type)
  1015. case <-time.After(5 * time.Second):
  1016. t.Fatal("parked fetcher was not released by the boot")
  1017. }
  1018. }
  1019. // A session tearing itself down — endSession, or the idle reaper — needs no
  1020. // sessionEnded event: the client already knows it is leaving. Close closes the
  1021. // queue before the instance, so the listener's push lands on a closed queue.
  1022. func TestSession_SelfCloseEmitsNoSessionEndedEvent(t *testing.T) {
  1023. mgr := NewSessionManager()
  1024. inst := state.NewSession().AddInstance()
  1025. sess, err := mgr.CreateSession(state.DisplayScreenName("mike"), []string{"presence"}, inst, "", slog.Default())
  1026. require.NoError(t, err)
  1027. sess.FeedbagLoader = emptyFeedbagLoader
  1028. sess.StartListeningToOSCARSession()
  1029. require.NoError(t, mgr.RemoveSession(context.Background(), sess.AimSID))
  1030. events, err := sess.EventQueue.Fetch(context.Background(), 0, time.Second)
  1031. require.NoError(t, err)
  1032. assert.Empty(t, events)
  1033. }
  1034. func TestSession_GetStoredIMs(t *testing.T) {
  1035. sess := &Session{}
  1036. sess.AddStoredIM("buddy1", "me", "hello", "msg-1", 100)
  1037. sess.AddStoredIM("buddy1", "buddy1", "hi back", "msg-2", 200)
  1038. sess.AddStoredIM("buddy2", "buddy2", "other chat", "msg-3", 150)
  1039. msgs := sess.GetStoredIMs(StoredIMQuery{
  1040. PartnerAimID: "buddy1",
  1041. SortOrder: "descendingDate",
  1042. NToGet: 10,
  1043. })
  1044. assert.Len(t, msgs, 2)
  1045. assert.Equal(t, "msg-2", msgs[0].MsgID)
  1046. assert.Equal(t, int64(200), msgs[0].Date)
  1047. assert.Equal(t, "hello", msgs[1].Message)
  1048. msgs = sess.GetStoredIMs(StoredIMQuery{
  1049. PartnerAimID: "buddy1",
  1050. SortOrder: "ascendingDate",
  1051. StartTime: 150,
  1052. EndTime: 250,
  1053. })
  1054. assert.Len(t, msgs, 1)
  1055. assert.Equal(t, "msg-2", msgs[0].MsgID)
  1056. }
  1057. func TestSession_GetStoredIMs_NormalizesPartner(t *testing.T) {
  1058. sess := &Session{}
  1059. sess.AddStoredIM("Mike Kelly", "mikekelly", "hello", "msg-1", 100)
  1060. // The web client queries history by the normalized aimId, never by the
  1061. // display screen name it was stored under.
  1062. msgs := sess.GetStoredIMs(StoredIMQuery{
  1063. PartnerAimID: "mikekelly",
  1064. NToGet: 10,
  1065. })
  1066. require.Len(t, msgs, 1)
  1067. assert.Equal(t, "msg-1", msgs[0].MsgID)
  1068. }
  1069. // A session gets no insert/update/delete SNAC for a feedbag change it made itself —
  1070. // those reach only a user's *other* instances. FeedbagStatus is the one notification
  1071. // it does receive, so it drives the roster event for the client's own edits.
  1072. func TestSession_FeedbagStatusRefreshesBuddyList(t *testing.T) {
  1073. tests := []struct {
  1074. name string
  1075. events []string
  1076. results []uint16
  1077. body any
  1078. wantEvent bool
  1079. }{
  1080. {
  1081. name: "stored item refreshes the roster",
  1082. events: []string{"buddylist"},
  1083. results: []uint16{0x0000},
  1084. wantEvent: true,
  1085. },
  1086. {
  1087. // The declined item is still worth a refresh: the roster is how the
  1088. // client discovers the buddy was not stored, since it is absent from it.
  1089. name: "declined item still refreshes the roster",
  1090. events: []string{"buddylist"},
  1091. results: []uint16{feedbagResultAuthRequired},
  1092. wantEvent: true,
  1093. },
  1094. {
  1095. name: "no event when not subscribed",
  1096. events: []string{"presence"},
  1097. results: []uint16{0x0000},
  1098. wantEvent: false,
  1099. },
  1100. {
  1101. name: "a body of the wrong type still refreshes",
  1102. events: []string{"buddylist"},
  1103. body: wire.SNAC_0x13_0x06_FeedbagReply{},
  1104. wantEvent: true,
  1105. },
  1106. }
  1107. for _, tt := range tests {
  1108. t.Run(tt.name, func(t *testing.T) {
  1109. refreshed := 0
  1110. sess := &Session{
  1111. ScreenName: state.DisplayScreenName("me"),
  1112. Events: tt.events,
  1113. EventQueue: NewEventQueue(10),
  1114. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  1115. BuddyListRefresher: func(_ context.Context) (any, error) {
  1116. refreshed++
  1117. return &BuddyListData{Groups: []BuddyGroup{}}, nil
  1118. },
  1119. FeedbagLoader: emptyFeedbagLoader,
  1120. }
  1121. body := tt.body
  1122. if body == nil {
  1123. body = wire.SNAC_0x13_0x0E_FeedbagStatus{Results: tt.results}
  1124. }
  1125. sess.handleFeedbagMessage(wire.SNACMessage{
  1126. Frame: wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagStatus},
  1127. Body: body,
  1128. })
  1129. var got int
  1130. for _, event := range sess.EventQueue.GetAllEvents() {
  1131. if event.Type == EventTypeBuddyList {
  1132. got++
  1133. }
  1134. }
  1135. if tt.wantEvent {
  1136. assert.Equal(t, 1, got)
  1137. assert.Equal(t, 1, refreshed)
  1138. } else {
  1139. assert.Zero(t, got)
  1140. assert.Zero(t, refreshed, "an unsubscribed session should not even query the roster")
  1141. }
  1142. })
  1143. }
  1144. }
  1145. func TestSession_HandleClientError(t *testing.T) {
  1146. const (
  1147. cookie = uint64(0xDEADBEEFCAFEF00D)
  1148. msgID = "11112222-3333-4444-8000-555566667777"
  1149. )
  1150. tests := []struct {
  1151. name string
  1152. // events is what the session subscribed to at startSession.
  1153. events []string
  1154. // record seeds the cookie->msgId map the way a prior im/sendIM would.
  1155. record bool
  1156. channelID uint16
  1157. wantEvent bool
  1158. wantCooki string
  1159. wantChan string
  1160. }{
  1161. {
  1162. name: "im channel names the message this session sent",
  1163. events: []string{"im"},
  1164. record: true,
  1165. channelID: wire.ICBMChannelIM,
  1166. wantEvent: true,
  1167. wantCooki: msgID,
  1168. wantChan: "im",
  1169. },
  1170. {
  1171. name: "rendezvous channel is reported as data",
  1172. events: []string{"im"},
  1173. record: true,
  1174. channelID: wire.ICBMChannelRendezvous,
  1175. wantEvent: true,
  1176. wantCooki: msgID,
  1177. wantChan: "data",
  1178. },
  1179. {
  1180. // Another instance of the account sent the message, so this session
  1181. // has no msgId for it and must not invent one.
  1182. name: "unknown cookie yields an empty msgId",
  1183. events: []string{"im"},
  1184. record: false,
  1185. channelID: wire.ICBMChannelIM,
  1186. wantEvent: true,
  1187. wantCooki: "",
  1188. wantChan: "im",
  1189. },
  1190. {
  1191. name: "not subscribed to im",
  1192. events: []string{"presence"},
  1193. record: true,
  1194. channelID: wire.ICBMChannelIM,
  1195. wantEvent: false,
  1196. },
  1197. }
  1198. for _, tt := range tests {
  1199. t.Run(tt.name, func(t *testing.T) {
  1200. sess := &Session{
  1201. Events: tt.events,
  1202. EventQueue: NewEventQueue(10),
  1203. FeedbagLoader: emptyFeedbagLoader,
  1204. }
  1205. if tt.record {
  1206. sess.RecordSentIM(cookie, msgID)
  1207. }
  1208. sess.handleSNACMessage(wire.SNACMessage{
  1209. Frame: wire.SNACFrame{
  1210. FoodGroup: wire.ICBM,
  1211. SubGroup: wire.ICBMClientErr,
  1212. },
  1213. Body: wire.SNAC_0x04_0x0B_ICBMClientErr{
  1214. Cookie: cookie,
  1215. ChannelID: tt.channelID,
  1216. ScreenName: "Mike Kelly",
  1217. Code: 0x0004,
  1218. },
  1219. })
  1220. events := sess.EventQueue.GetAllEvents()
  1221. if !tt.wantEvent {
  1222. assert.Empty(t, events)
  1223. return
  1224. }
  1225. require.Len(t, events, 1)
  1226. assert.Equal(t, EventTypeClientError, events[0].Type)
  1227. got := events[0].Data.(ClientErrorEvent)
  1228. assert.Equal(t, tt.wantCooki, got.Cookie)
  1229. assert.Equal(t, tt.wantChan, got.Channel)
  1230. // The client keys users by the normalized id and renders the sender's
  1231. // own formatting, so both forms have to survive the translation.
  1232. assert.Equal(t, "mikekelly", got.Source.AimID)
  1233. assert.Equal(t, "Mike Kelly", got.Source.DisplayID)
  1234. })
  1235. }
  1236. }
  1237. func TestSession_RecordSentIMEvictsOldestCookie(t *testing.T) {
  1238. sess := &Session{}
  1239. for i := 0; i <= sentIMCookieLimit; i++ {
  1240. sess.RecordSentIM(uint64(i), fmt.Sprintf("msg-%d", i))
  1241. }
  1242. // The map is capped, so the oldest send is forgotten while the newest and the
  1243. // one that pushed the map over its limit are both still resolvable.
  1244. assert.Equal(t, "", sess.msgIDForCookie(0))
  1245. assert.Equal(t, "msg-1", sess.msgIDForCookie(1))
  1246. assert.Equal(t, fmt.Sprintf("msg-%d", sentIMCookieLimit), sess.msgIDForCookie(uint64(sentIMCookieLimit)))
  1247. assert.Len(t, sess.sentIMs, sentIMCookieLimit)
  1248. // A repeat cookie updates in place rather than consuming another slot.
  1249. sess.RecordSentIM(1, "msg-1-again")
  1250. assert.Equal(t, "msg-1-again", sess.msgIDForCookie(1))
  1251. assert.Len(t, sess.sentIMs, sentIMCookieLimit)
  1252. }
  1253. // A buddy's mood rides along in the capability list of a BuddyArrived, so the
  1254. // presence event has to carry it as a mood icon URL.
  1255. func TestSession_PublishesMoodOnPresence(t *testing.T) {
  1256. newSession := func() *Session {
  1257. return &Session{
  1258. ScreenName: state.DisplayScreenName("me"),
  1259. BaseURL: "http://host",
  1260. Events: []string{"presence"},
  1261. EventQueue: NewEventQueue(10),
  1262. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  1263. FeedbagLoader: emptyFeedbagLoader,
  1264. }
  1265. }
  1266. // arrived delivers a BuddyArrived carrying a raw capabilities TLV value.
  1267. arrived := func(sess *Session, caps []byte, invisible bool) PresenceEvent {
  1268. info := wire.TLVUserInfo{ScreenName: "Mike Kelly"}
  1269. if caps != nil {
  1270. info.Append(wire.NewTLVBE(wire.OServiceUserInfoOscarCaps, caps))
  1271. }
  1272. if invisible {
  1273. info.Append(wire.NewTLVBE(wire.OServiceUserInfoStatus, wire.OServiceUserStatusInvisible))
  1274. }
  1275. sess.handleBuddyArrived(wire.SNACMessage{Body: wire.SNAC_0x03_0x0B_BuddyArrived{TLVUserInfo: info}})
  1276. events := sess.EventQueue.GetAllEvents()
  1277. require.Len(t, events, 1)
  1278. return events[0].Data.(PresenceEvent)
  1279. }
  1280. capBytes := func(caps ...[16]byte) []byte {
  1281. var b []byte
  1282. for _, c := range caps {
  1283. b = append(b, c[:]...)
  1284. }
  1285. return b
  1286. }
  1287. t.Run("a mood capability yields the mood icon URL", func(t *testing.T) {
  1288. got := arrived(newSession(), capBytes(wire.CapXStatusBeer), false)
  1289. assert.Equal(t, "http://host/mood?id="+wire.MoodIconID("0icqmood4"), got.MoodIcon)
  1290. })
  1291. t.Run("a placeholder capability resolves too", func(t *testing.T) {
  1292. got := arrived(newSession(), capBytes(wire.CapMoodOnTheWay), false)
  1293. assert.Equal(t, "http://host/mood?id="+wire.MoodIconID("0icqmood83"), got.MoodIcon)
  1294. })
  1295. t.Run("a shared capability resolves to the canonical mood", func(t *testing.T) {
  1296. // Console is reachable from 0icqmood15 and 0icqmood81; the table's first
  1297. // entry wins, so the client is told the one it labels "gamepad".
  1298. got := arrived(newSession(), capBytes(wire.CapXStatusConsole), false)
  1299. assert.Equal(t, "http://host/mood?id="+wire.MoodIconID("0icqmood81"), got.MoodIcon)
  1300. })
  1301. t.Run("a mood is found after other capabilities", func(t *testing.T) {
  1302. got := arrived(newSession(), capBytes(wire.CapChat, wire.CapXStatusBeer), false)
  1303. assert.Equal(t, "http://host/mood?id="+wire.MoodIconID("0icqmood4"), got.MoodIcon)
  1304. })
  1305. t.Run("capabilities carrying no mood yield no icon", func(t *testing.T) {
  1306. assert.Empty(t, arrived(newSession(), capBytes(wire.CapChat), false).MoodIcon)
  1307. })
  1308. t.Run("no capabilities TLV yields no icon", func(t *testing.T) {
  1309. assert.Empty(t, arrived(newSession(), nil, false).MoodIcon)
  1310. })
  1311. t.Run("a trailing partial capability is ignored", func(t *testing.T) {
  1312. // A truncated final chunk must not be read as a capability, nor panic.
  1313. truncated := append(capBytes(wire.CapXStatusBeer), 0x01, 0x02, 0x03)
  1314. got := arrived(newSession(), truncated, false)
  1315. assert.Equal(t, "http://host/mood?id="+wire.MoodIconID("0icqmood4"), got.MoodIcon)
  1316. })
  1317. t.Run("a partial capability alone yields no icon", func(t *testing.T) {
  1318. assert.Empty(t, arrived(newSession(), []byte{0x01, 0x02, 0x03}, false).MoodIcon)
  1319. })
  1320. t.Run("an invisible buddy shows no mood", func(t *testing.T) {
  1321. // A mood supersedes state on the client, so one here would render the
  1322. // buddy as present instead of offline.
  1323. got := arrived(newSession(), capBytes(wire.CapXStatusBeer), true)
  1324. assert.Equal(t, "offline", got.State)
  1325. assert.Empty(t, got.MoodIcon)
  1326. })
  1327. }
  1328. func TestSession_SetMood(t *testing.T) {
  1329. t.Run("advertises the mood alongside the existing capabilities", func(t *testing.T) {
  1330. sess := &Session{capabilities: [][16]byte{wire.CapChat}}
  1331. sess.SetMood(wire.CapXStatusBeer)
  1332. assert.Equal(t, [][16]byte{wire.CapChat, wire.CapXStatusBeer}, sess.Caps())
  1333. })
  1334. t.Run("a second mood replaces the first", func(t *testing.T) {
  1335. // A client shows one mood at a time, so the moods must not accumulate.
  1336. sess := &Session{capabilities: [][16]byte{wire.CapChat}}
  1337. sess.SetMood(wire.CapXStatusBeer)
  1338. sess.SetMood(wire.CapXStatusMusic)
  1339. assert.Equal(t, [][16]byte{wire.CapChat, wire.CapXStatusMusic}, sess.Caps())
  1340. })
  1341. t.Run("panics on a capability that is not a mood", func(t *testing.T) {
  1342. sess := &Session{}
  1343. assert.Panics(t, func() {
  1344. sess.SetMood(wire.CapChat)
  1345. })
  1346. })
  1347. }
  1348. func TestSession_ClearMood(t *testing.T) {
  1349. t.Run("removes the mood and keeps every other capability", func(t *testing.T) {
  1350. sess := &Session{capabilities: [][16]byte{wire.CapChat, wire.CapFileTransfer}}
  1351. sess.SetMood(wire.CapXStatusBeer)
  1352. sess.ClearMood()
  1353. assert.Equal(t, [][16]byte{wire.CapChat, wire.CapFileTransfer}, sess.Caps())
  1354. })
  1355. t.Run("is a no-op when no mood is set", func(t *testing.T) {
  1356. sess := &Session{capabilities: [][16]byte{wire.CapChat}}
  1357. sess.ClearMood()
  1358. assert.Equal(t, [][16]byte{wire.CapChat}, sess.Caps())
  1359. })
  1360. }
  1361. func TestSession_Caps(t *testing.T) {
  1362. t.Run("returns a copy the caller cannot write through", func(t *testing.T) {
  1363. sess := &Session{capabilities: [][16]byte{wire.CapChat}}
  1364. caps := sess.Caps()
  1365. caps[0] = wire.CapFileTransfer
  1366. assert.Equal(t, [][16]byte{wire.CapChat}, sess.Caps())
  1367. })
  1368. t.Run("a session advertising no capabilities returns an empty list", func(t *testing.T) {
  1369. assert.Empty(t, (&Session{}).Caps())
  1370. })
  1371. }
  1372. func TestSessionManager_CreateSession_SeedsCapabilities(t *testing.T) {
  1373. // setStatus rewrites the capability list wholesale from the session's own
  1374. // list, so the sign-on capabilities have to start out in it.
  1375. mgr := NewSessionManager()
  1376. logger := slog.New(slog.NewTextHandler(io.Discard, nil))
  1377. sess, err := mgr.CreateSession("testuser", nil, state.NewSession().AddInstance(), "", logger)
  1378. require.NoError(t, err)
  1379. sess.FeedbagLoader = emptyFeedbagLoader
  1380. assert.Equal(t, webAPICaps, sess.Caps())
  1381. sess.SetMood(wire.CapXStatusBeer)
  1382. other, err := mgr.CreateSession("otheruser", nil, state.NewSession().AddInstance(), "", logger)
  1383. require.NoError(t, err)
  1384. other.FeedbagLoader = emptyFeedbagLoader
  1385. assert.Equal(t, webAPICaps, other.Caps(), "one session's mood must not reach the next session's seed")
  1386. }
  1387. // An IM does not change its sender's presence, and the client shallow-merges the
  1388. // source user map onto the user object the buddy list rendered.
  1389. func TestSession_IncomingIMReportsSenderPresenceFromTheView(t *testing.T) {
  1390. newSession := func() *Session {
  1391. return &Session{
  1392. ScreenName: state.DisplayScreenName("me"),
  1393. Events: []string{"im", "presence"},
  1394. EventQueue: NewEventQueue(10),
  1395. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  1396. FeedbagLoader: emptyFeedbagLoader,
  1397. }
  1398. }
  1399. incomingIM := func(t *testing.T, sess *Session, from string) IMEvent {
  1400. t.Helper()
  1401. frags, err := wire.ICBMFragmentList("hello")
  1402. require.NoError(t, err)
  1403. body := wire.SNAC_0x04_0x07_ICBMChannelMsgToClient{
  1404. ChannelID: wire.ICBMChannelIM,
  1405. TLVUserInfo: wire.TLVUserInfo{ScreenName: from},
  1406. }
  1407. body.Append(wire.NewTLVBE(wire.ICBMTLVAOLIMData, frags))
  1408. sess.handleIncomingIM(wire.SNACMessage{Body: body})
  1409. for _, event := range sess.EventQueue.GetAllEvents() {
  1410. if im, ok := event.Data.(IMEvent); ok {
  1411. return im
  1412. }
  1413. }
  1414. t.Fatal("no im event was pushed")
  1415. return IMEvent{}
  1416. }
  1417. t.Run("an away sender stays away", func(t *testing.T) {
  1418. sess := newSession()
  1419. away := wire.TLVUserInfo{ScreenName: "Mike Kelly"}
  1420. away.Append(wire.NewTLVBE(wire.OServiceUserInfoUserFlags, wire.OServiceUserFlagUnavailable))
  1421. buddyArrives(sess, away)
  1422. assert.Equal(t, "away", incomingIM(t, sess, "Mike Kelly").Source.State)
  1423. })
  1424. t.Run("a busy ICQ sender stays occupied", func(t *testing.T) {
  1425. sess := newSession()
  1426. sess.ScreenName = state.DisplayScreenName("100001")
  1427. busy := wire.TLVUserInfo{ScreenName: "100003"}
  1428. busy.Append(wire.NewTLVBE(wire.OServiceUserInfoStatus, wire.OServiceUserStatusBusy))
  1429. buddyArrives(sess, busy)
  1430. assert.Equal(t, "occupied", incomingIM(t, sess, "100003").Source.State)
  1431. })
  1432. t.Run("an online sender is online", func(t *testing.T) {
  1433. sess := newSession()
  1434. buddyArrives(sess, onlineBuddy("Mike Kelly"))
  1435. assert.Equal(t, "online", incomingIM(t, sess, "Mike Kelly").Source.State)
  1436. })
  1437. // A non-buddy raises no arrival, so there is no state to report.
  1438. t.Run("a sender with no presence carries no state", func(t *testing.T) {
  1439. sess := newSession()
  1440. assert.Empty(t, incomingIM(t, sess, "stranger").Source.State)
  1441. })
  1442. }
  1443. // userInfoWith builds the user info a buddy arrives with.
  1444. func userInfoWith(screenName string, tlvs ...wire.TLV) wire.TLVUserInfo {
  1445. info := wire.TLVUserInfo{ScreenName: screenName}
  1446. for _, tlv := range tlvs {
  1447. info.Append(tlv)
  1448. }
  1449. return info
  1450. }
  1451. func awayFlagTLV() wire.TLV {
  1452. return wire.NewTLVBE(wire.OServiceUserInfoUserFlags, wire.OServiceUserFlagUnavailable)
  1453. }
  1454. func statusTLV(mask uint32) wire.TLV {
  1455. return wire.NewTLVBE(wire.OServiceUserInfoStatus, mask)
  1456. }
  1457. func idleTLV(minutes uint16) wire.TLV {
  1458. return wire.NewTLVBE(wire.OServiceUserInfoIdleTime, minutes)
  1459. }
  1460. func TestBuddyWebState(t *testing.T) {
  1461. tests := []struct {
  1462. name string
  1463. info wire.TLVUserInfo
  1464. isAIMViewer bool
  1465. wantState string
  1466. wantIdle int
  1467. }{
  1468. {
  1469. name: "a plain arrival is online",
  1470. info: userInfoWith("buddy"),
  1471. isAIMViewer: true,
  1472. wantState: "online",
  1473. },
  1474. {
  1475. // A buddy cannot tell an invisible user from a signed-off one.
  1476. name: "invisible reads as offline",
  1477. info: userInfoWith("buddy", statusTLV(wire.OServiceUserStatusInvisible)),
  1478. isAIMViewer: true,
  1479. wantState: "offline",
  1480. },
  1481. {
  1482. name: "the unavailable flag is away",
  1483. info: userInfoWith("buddy", awayFlagTLV()),
  1484. isAIMViewer: true,
  1485. wantState: "away",
  1486. },
  1487. {
  1488. name: "the away status bit is away",
  1489. info: userInfoWith("buddy", statusTLV(wire.OServiceUserStatusAway)),
  1490. isAIMViewer: true,
  1491. wantState: "away",
  1492. },
  1493. {
  1494. // Busy and DND also raise the unavailable flag, so the status bits
  1495. // have to be read first or every busy user reports as away.
  1496. name: "busy reaches an ICQ viewer as occupied",
  1497. info: userInfoWith("buddy", statusTLV(wire.OServiceUserStatusBusy), awayFlagTLV()),
  1498. isAIMViewer: false,
  1499. wantState: "occupied",
  1500. },
  1501. {
  1502. name: "dnd reaches an ICQ viewer as dnd",
  1503. info: userInfoWith("buddy", statusTLV(wire.OServiceUserStatusDND), awayFlagTLV()),
  1504. isAIMViewer: false,
  1505. wantState: "dnd",
  1506. },
  1507. {
  1508. // AIM accounts have no vocabulary for busy or dnd.
  1509. name: "busy collapses to away for an AIM viewer",
  1510. info: userInfoWith("buddy", statusTLV(wire.OServiceUserStatusBusy), awayFlagTLV()),
  1511. isAIMViewer: true,
  1512. wantState: "away",
  1513. },
  1514. {
  1515. name: "dnd collapses to away for an AIM viewer",
  1516. info: userInfoWith("buddy", statusTLV(wire.OServiceUserStatusDND), awayFlagTLV()),
  1517. isAIMViewer: true,
  1518. wantState: "away",
  1519. },
  1520. {
  1521. name: "idle alone is idle",
  1522. info: userInfoWith("buddy", idleTLV(7)),
  1523. isAIMViewer: true,
  1524. wantState: "idle",
  1525. wantIdle: 7,
  1526. },
  1527. {
  1528. // Idle rides along in idleTime without taking over the state.
  1529. name: "idle does not displace away",
  1530. info: userInfoWith("buddy", awayFlagTLV(), idleTLV(12)),
  1531. isAIMViewer: true,
  1532. wantState: "away",
  1533. wantIdle: 12,
  1534. },
  1535. {
  1536. name: "idle does not displace occupied",
  1537. info: userInfoWith("buddy", statusTLV(wire.OServiceUserStatusBusy), awayFlagTLV(), idleTLV(3)),
  1538. isAIMViewer: false,
  1539. wantState: "occupied",
  1540. wantIdle: 3,
  1541. },
  1542. {
  1543. name: "zero idle minutes leave the buddy online",
  1544. info: userInfoWith("buddy", idleTLV(0)),
  1545. isAIMViewer: true,
  1546. wantState: "online",
  1547. },
  1548. }
  1549. for _, tt := range tests {
  1550. t.Run(tt.name, func(t *testing.T) {
  1551. gotState, gotIdle := buddyWebState(tt.info, tt.isAIMViewer)
  1552. assert.Equal(t, tt.wantState, gotState)
  1553. assert.Equal(t, tt.wantIdle, gotIdle)
  1554. })
  1555. }
  1556. }
  1557. // No locate query follows a presence record, so everything a roster payload
  1558. // needs has to survive the trip from the SNAC.
  1559. func TestBuddyPresenceFrom(t *testing.T) {
  1560. info := userInfoWith("Mike Kelly", idleTLV(4),
  1561. wire.NewTLVBE(wire.OServiceUserInfoSignonTOD, uint32(1700000000)),
  1562. wire.NewTLVBE(wire.OServiceUserInfoOscarCaps, wire.CapICQCh2Extended[:]),
  1563. wire.NewTLVBE(wire.OServiceUserInfoBARTInfo, []wire.BARTID{testIconBART, testStatusBART}),
  1564. )
  1565. got := buddyPresenceFrom(info, true)
  1566. assert.Equal(t, "Mike Kelly", got.DisplayID)
  1567. assert.Equal(t, "idle", got.State)
  1568. assert.Equal(t, 4, got.IdleTime)
  1569. assert.Equal(t, int64(1700000000), got.OnlineTime)
  1570. assert.Equal(t, "brb", got.StatusMsg)
  1571. assert.Equal(t, [][16]byte{wire.CapICQCh2Extended}, got.Caps)
  1572. assert.Equal(t, []byte{0xde, 0xad, 0xbe, 0xef}, got.IconHash)
  1573. assert.True(t, got.Online())
  1574. }
  1575. func TestSession_PresenceView(t *testing.T) {
  1576. newSession := func(events ...string) *Session {
  1577. return &Session{
  1578. ScreenName: state.DisplayScreenName("me"),
  1579. Events: events,
  1580. EventQueue: NewEventQueue(10),
  1581. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  1582. FeedbagLoader: emptyFeedbagLoader,
  1583. }
  1584. }
  1585. t.Run("an arrival records the buddy under their normalized aimId", func(t *testing.T) {
  1586. sess := newSession("presence")
  1587. buddyArrives(sess, onlineBuddy("Mike Kelly"))
  1588. got, ok := sess.BuddyPresence(state.NewIdentScreenName("MIKE KELLY"))
  1589. require.True(t, ok)
  1590. assert.Equal(t, "online", got.State)
  1591. assert.Equal(t, "Mike Kelly", got.DisplayID)
  1592. })
  1593. t.Run("a buddy never seen has no entry", func(t *testing.T) {
  1594. sess := newSession("presence")
  1595. _, ok := sess.BuddyPresence(state.NewIdentScreenName("stranger"))
  1596. assert.False(t, ok)
  1597. })
  1598. // A departure carries no TLV block, so everything but the display name goes.
  1599. t.Run("a departure marks the buddy offline and keeps their display name", func(t *testing.T) {
  1600. sess := newSession("presence")
  1601. buddyArrives(sess, bartBuddy("Mike Kelly", testIconBART, testStatusBART))
  1602. buddyDeparts(sess, "mikekelly")
  1603. got, ok := sess.BuddyPresence(state.NewIdentScreenName("mikekelly"))
  1604. require.True(t, ok)
  1605. assert.Equal(t, "offline", got.State)
  1606. assert.Equal(t, "Mike Kelly", got.DisplayID)
  1607. assert.Empty(t, got.StatusMsg)
  1608. assert.Empty(t, got.IconHash)
  1609. assert.False(t, got.Online())
  1610. })
  1611. t.Run("a later arrival replaces the earlier state", func(t *testing.T) {
  1612. sess := newSession("presence")
  1613. buddyArrives(sess, onlineBuddy("mikekelly"))
  1614. buddyArrives(sess, userInfoWith("mikekelly", awayFlagTLV()))
  1615. got, _ := sess.BuddyPresence(state.NewIdentScreenName("mikekelly"))
  1616. assert.Equal(t, "away", got.State)
  1617. })
  1618. // The roster reads this view, so a buddylist-only client still needs it.
  1619. t.Run("the view is recorded without a presence subscription", func(t *testing.T) {
  1620. sess := newSession("buddylist")
  1621. buddyArrives(sess, onlineBuddy("mikekelly"))
  1622. got, ok := sess.BuddyPresence(state.NewIdentScreenName("mikekelly"))
  1623. require.True(t, ok)
  1624. assert.Equal(t, "online", got.State)
  1625. assert.Empty(t, sess.EventQueue.GetAllEvents())
  1626. buddyDeparts(sess, "mikekelly")
  1627. got, _ = sess.BuddyPresence(state.NewIdentScreenName("mikekelly"))
  1628. assert.Equal(t, "offline", got.State)
  1629. assert.Empty(t, sess.EventQueue.GetAllEvents())
  1630. })
  1631. // A UIN viewer keeps ICQ's own vocabulary; an AIM viewer does not.
  1632. t.Run("the viewer's account type decides how busy is reported", func(t *testing.T) {
  1633. busy := userInfoWith("100003", statusTLV(wire.OServiceUserStatusBusy), awayFlagTLV())
  1634. aimViewer := newSession("presence")
  1635. buddyArrives(aimViewer, busy)
  1636. got, _ := aimViewer.BuddyPresence(state.NewIdentScreenName("100003"))
  1637. assert.Equal(t, "away", got.State)
  1638. icqViewer := newSession("presence")
  1639. icqViewer.ScreenName = state.DisplayScreenName("100001")
  1640. buddyArrives(icqViewer, busy)
  1641. got, _ = icqViewer.BuddyPresence(state.NewIdentScreenName("100003"))
  1642. assert.Equal(t, "occupied", got.State)
  1643. })
  1644. }
  1645. // Idle time and signon time have fields on the presence event and come from the
  1646. // same record the roster reads.
  1647. func TestSession_PresenceEventCarriesIdleAndOnlineTime(t *testing.T) {
  1648. sess := &Session{
  1649. ScreenName: state.DisplayScreenName("me"),
  1650. Events: []string{"presence"},
  1651. EventQueue: NewEventQueue(10),
  1652. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  1653. FeedbagLoader: emptyFeedbagLoader,
  1654. }
  1655. buddyArrives(sess, userInfoWith("mikekelly", idleTLV(9),
  1656. wire.NewTLVBE(wire.OServiceUserInfoSignonTOD, uint32(1700000000))))
  1657. events := sess.EventQueue.GetAllEvents()
  1658. require.Len(t, events, 1)
  1659. got := events[0].Data.(PresenceEvent)
  1660. assert.Equal(t, "idle", got.State)
  1661. assert.Equal(t, 9, got.IdleTime)
  1662. assert.Equal(t, int64(1700000000), got.OnlineTime)
  1663. }
  1664. // After un-watching a buddy, no arrival or departure for them reaches this
  1665. // session again, so a retained entry would serve its last-seen state forever.
  1666. func TestSession_ForgetBuddyPresence(t *testing.T) {
  1667. newSession := func() *Session {
  1668. return &Session{
  1669. ScreenName: state.DisplayScreenName("me"),
  1670. Events: []string{"presence", "im"},
  1671. EventQueue: NewEventQueue(10),
  1672. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  1673. FeedbagLoader: emptyFeedbagLoader,
  1674. }
  1675. }
  1676. t.Run("forgetting drops the entry rather than marking it offline", func(t *testing.T) {
  1677. sess := newSession()
  1678. buddyArrives(sess, onlineBuddy("Mike Kelly"))
  1679. sess.forgetBuddyPresence(state.NewIdentScreenName("mikekelly"))
  1680. // A miss, not an offline record: callers that can fall back to a live
  1681. // lookup have to tell the two apart.
  1682. _, ok := sess.BuddyPresence(state.NewIdentScreenName("mikekelly"))
  1683. assert.False(t, ok)
  1684. })
  1685. t.Run("forgetting an unknown buddy is a no-op", func(t *testing.T) {
  1686. sess := newSession()
  1687. sess.forgetBuddyPresence(state.NewIdentScreenName("stranger"))
  1688. _, ok := sess.BuddyPresence(state.NewIdentScreenName("stranger"))
  1689. assert.False(t, ok)
  1690. })
  1691. t.Run("a later arrival re-establishes the entry", func(t *testing.T) {
  1692. sess := newSession()
  1693. buddyArrives(sess, onlineBuddy("mikekelly"))
  1694. sess.forgetBuddyPresence(state.NewIdentScreenName("mikekelly"))
  1695. buddyArrives(sess, onlineBuddy("mikekelly"))
  1696. got, ok := sess.BuddyPresence(state.NewIdentScreenName("mikekelly"))
  1697. require.True(t, ok)
  1698. assert.Equal(t, "online", got.State)
  1699. })
  1700. // While watched a departure would have arrived; after un-watching none does.
  1701. t.Run("an IM from a forgotten buddy carries no state", func(t *testing.T) {
  1702. sess := newSession()
  1703. buddyArrives(sess, onlineBuddy("Mike Kelly"))
  1704. sess.forgetBuddyPresence(state.NewIdentScreenName("mikekelly"))
  1705. frags, err := wire.ICBMFragmentList("hello")
  1706. require.NoError(t, err)
  1707. body := wire.SNAC_0x04_0x07_ICBMChannelMsgToClient{
  1708. ChannelID: wire.ICBMChannelIM,
  1709. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  1710. }
  1711. body.Append(wire.NewTLVBE(wire.ICBMTLVAOLIMData, frags))
  1712. sess.handleIncomingIM(wire.SNACMessage{Body: body})
  1713. for _, event := range sess.EventQueue.GetAllEvents() {
  1714. if im, ok := event.Data.(IMEvent); ok {
  1715. assert.Empty(t, im.Source.State)
  1716. return
  1717. }
  1718. }
  1719. t.Fatal("no im event was pushed")
  1720. })
  1721. }
  1722. // A relayed delete names the items that went away, not whether the buddy left the
  1723. // roster, so only a buddy absent from the refreshed roster is forgotten.
  1724. func TestSession_RelayedFeedbagDeleteForgetsUnlistedBuddies(t *testing.T) {
  1725. newSession := func(roster ...string) *Session {
  1726. sess := &Session{
  1727. ScreenName: state.DisplayScreenName("me"),
  1728. Events: []string{"presence", "buddylist"},
  1729. EventQueue: NewEventQueue(10),
  1730. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  1731. FeedbagLoader: emptyFeedbagLoader,
  1732. }
  1733. sess.ctx = context.Background()
  1734. sess.FeedbagLoader = func(context.Context) ([]wire.FeedbagItem, error) {
  1735. items := make([]wire.FeedbagItem, 0, len(roster))
  1736. for i, name := range roster {
  1737. items = append(items, wire.FeedbagItem{
  1738. ItemID: uint16(i + 1), ClassID: wire.FeedbagClassIdBuddy, GroupID: 100, Name: name,
  1739. })
  1740. }
  1741. return items, nil
  1742. }
  1743. return sess
  1744. }
  1745. relayDelete := func(sess *Session, items ...wire.FeedbagItem) {
  1746. sess.handleFeedbagMessage(wire.SNACMessage{
  1747. Frame: wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagDeleteItem},
  1748. Body: wire.SNAC_0x13_0x0A_FeedbagDeleteItem{Items: items},
  1749. })
  1750. }
  1751. buddyItem := wire.FeedbagItem{ClassID: wire.FeedbagClassIdBuddy, Name: "mikekelly"}
  1752. t.Run("a buddy gone from the roster is forgotten", func(t *testing.T) {
  1753. sess := newSession()
  1754. buddyArrives(sess, onlineBuddy("Mike Kelly"))
  1755. relayDelete(sess, buddyItem)
  1756. _, ok := sess.BuddyPresence(state.NewIdentScreenName("mikekelly"))
  1757. assert.False(t, ok)
  1758. })
  1759. // The move case: a delete for the old group's item, then an insert.
  1760. t.Run("a buddy still on the roster keeps their entry", func(t *testing.T) {
  1761. sess := newSession("mikekelly")
  1762. buddyArrives(sess, onlineBuddy("Mike Kelly"))
  1763. relayDelete(sess, buddyItem)
  1764. got, ok := sess.BuddyPresence(state.NewIdentScreenName("mikekelly"))
  1765. require.True(t, ok)
  1766. assert.Equal(t, "online", got.State)
  1767. })
  1768. t.Run("a group row does not evict a like-named buddy", func(t *testing.T) {
  1769. sess := newSession()
  1770. buddyArrives(sess, onlineBuddy("keeper"))
  1771. relayDelete(sess, wire.FeedbagItem{ClassID: wire.FeedbagClassIdGroup, Name: "keeper"})
  1772. _, ok := sess.BuddyPresence(state.NewIdentScreenName("keeper"))
  1773. assert.True(t, ok)
  1774. })
  1775. // Without a roster the two cases are indistinguishable, so nothing is dropped.
  1776. t.Run("a roster lookup failure keeps the entry", func(t *testing.T) {
  1777. sess := newSession()
  1778. sess.FeedbagLoader = func(context.Context) ([]wire.FeedbagItem, error) {
  1779. return nil, io.ErrUnexpectedEOF
  1780. }
  1781. buddyArrives(sess, onlineBuddy("Mike Kelly"))
  1782. relayDelete(sess, buddyItem)
  1783. _, ok := sess.BuddyPresence(state.NewIdentScreenName("mikekelly"))
  1784. assert.True(t, ok)
  1785. })
  1786. }
  1787. // An insert or update leaves the roster membership intact, so it must not evict.
  1788. func TestSession_RelayedFeedbagUpdateKeepsPresence(t *testing.T) {
  1789. sess := &Session{
  1790. ScreenName: state.DisplayScreenName("me"),
  1791. Events: []string{"presence", "buddylist"},
  1792. EventQueue: NewEventQueue(10),
  1793. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  1794. FeedbagLoader: emptyFeedbagLoader,
  1795. }
  1796. buddyArrives(sess, onlineBuddy("Mike Kelly"))
  1797. sess.handleFeedbagMessage(wire.SNACMessage{
  1798. Frame: wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagUpdateItem},
  1799. Body: wire.SNAC_0x13_0x09_FeedbagUpdateItem{Items: []wire.FeedbagItem{
  1800. {ClassID: wire.FeedbagClassIdBuddy, Name: "mikekelly"},
  1801. }},
  1802. })
  1803. got, ok := sess.BuddyPresence(state.NewIdentScreenName("mikekelly"))
  1804. require.True(t, ok)
  1805. assert.Equal(t, "online", got.State)
  1806. }
  1807. // The roster, its aliases and the membership check a relayed delete makes are three
  1808. // views of the same rows, so one feedbag change must cost one read.
  1809. func TestSession_FeedbagCacheServesEveryReadFromOneLoad(t *testing.T) {
  1810. var loads int
  1811. sess := &Session{
  1812. ScreenName: state.DisplayScreenName("me"),
  1813. Events: []string{"presence", "buddylist"},
  1814. EventQueue: NewEventQueue(10),
  1815. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  1816. FeedbagLoader: emptyFeedbagLoader,
  1817. }
  1818. sess.ctx = context.Background()
  1819. sess.FeedbagLoader = func(context.Context) ([]wire.FeedbagItem, error) {
  1820. loads++
  1821. return aliasFeedbagItems(map[string]string{"keeper": "KEEPER"}), nil
  1822. }
  1823. buddyArrives(sess, onlineBuddy("keeper"))
  1824. buddyArrives(sess, onlineBuddy("gone"))
  1825. require.Equal(t, 1, loads, "arrivals resolve aliases off one load")
  1826. sess.handleFeedbagMessage(wire.SNACMessage{
  1827. Frame: wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagDeleteItem},
  1828. Body: wire.SNAC_0x13_0x0A_FeedbagDeleteItem{Items: []wire.FeedbagItem{
  1829. {ClassID: wire.FeedbagClassIdBuddy, Name: "gone"},
  1830. {ClassID: wire.FeedbagClassIdBuddy, Name: "keeper"},
  1831. }},
  1832. })
  1833. assert.Equal(t, 2, loads, "one reload serves the whole handler")
  1834. _, ok := sess.BuddyPresence(state.NewIdentScreenName("gone"))
  1835. assert.False(t, ok)
  1836. _, ok = sess.BuddyPresence(state.NewIdentScreenName("keeper"))
  1837. assert.True(t, ok)
  1838. assert.Equal(t, "KEEPER", sess.Aliases(context.Background())["keeper"])
  1839. _, err := sess.Feedbag(context.Background())
  1840. require.NoError(t, err)
  1841. assert.Equal(t, 2, loads)
  1842. }