session_test.go 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340
  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. }
  76. }
  77. rateSNAC := func(classID uint16, code uint16) wire.SNACMessage {
  78. return wire.SNACMessage{
  79. Frame: wire.SNACFrame{FoodGroup: wire.OService, SubGroup: wire.OServiceRateParamChange},
  80. Body: wire.SNAC_0x01_0x0A_OServiceRateParamsChange{Code: code, Rate: wire.RateParamsSNAC{ID: classID}},
  81. }
  82. }
  83. t.Run("IM-class transitions become rateLimit events", func(t *testing.T) {
  84. sess := newSession()
  85. sess.handleSNACMessage(rateSNAC(uint16(imClass), 3)) // limited
  86. sess.handleSNACMessage(rateSNAC(uint16(imClass), 4)) // clear
  87. events := sess.EventQueue.GetAllEvents()
  88. require.Len(t, events, 2)
  89. assert.Equal(t, "limit", events[0].Data.(RateLimitEvent).Classes[0].Status)
  90. assert.Equal(t, "clear", events[1].Data.(RateLimitEvent).Classes[0].Status)
  91. })
  92. t.Run("other classes and non-status codes are ignored", func(t *testing.T) {
  93. sess := newSession()
  94. sess.handleSNACMessage(rateSNAC(1, 3)) // class 1 limited: not the IM class
  95. sess.handleSNACMessage(rateSNAC(uint16(imClass), 1)) // IM class param change, not a status
  96. assert.Empty(t, sess.EventQueue.GetAllEvents())
  97. })
  98. t.Run("a session with no IM class disables the alert", func(t *testing.T) {
  99. sess := newSession()
  100. sess.IMRateClassID = 0
  101. sess.handleSNACMessage(rateSNAC(uint16(imClass), 3))
  102. assert.Empty(t, sess.EventQueue.GetAllEvents())
  103. })
  104. }
  105. // A rate-limit disconnect closes the account's OSCAR session; the web session's
  106. // aimsid must then stop resolving. Before this fix GetSession only checked
  107. // time-based expiry, so a client told to disconnect could keep issuing charged
  108. // requests against a dead session (and, downstream, spam clear events on every
  109. // one of them). Once the aimsid is turned away at RequireSession, neither is
  110. // possible.
  111. func TestSessionManager_GetSession_rejectsAfterRateLimitDisconnect(t *testing.T) {
  112. mgr := NewSessionManager()
  113. // A rate class that escalates to disconnect after a short back-to-back burst.
  114. var classes [5]wire.RateClass
  115. for i := range classes {
  116. classes[i] = wire.RateClass{
  117. ID: wire.RateLimitClassID(i + 1),
  118. WindowSize: 2,
  119. ClearLevel: 100,
  120. AlertLevel: 80,
  121. LimitLevel: 70,
  122. DisconnectLevel: 2,
  123. MaxLevel: 200,
  124. }
  125. }
  126. inst := state.NewSession().AddInstance()
  127. inst.Session().SetRateClasses(time.Now(), wire.NewRateLimitClasses(classes))
  128. sess, err := mgr.CreateSession(state.DisplayScreenName("advbot"), []string{"presence"}, inst, "", slog.Default())
  129. require.NoError(t, err)
  130. // Healthy session resolves.
  131. got, err := mgr.GetSession(context.Background(), sess.AimSID)
  132. require.NoError(t, err)
  133. assert.Same(t, sess, got)
  134. // Burst until EvaluateRateLimit escalates to disconnect, which closes the
  135. // account's OSCAR session.
  136. var status wire.RateLimitStatus
  137. now := time.Now()
  138. for range 10 {
  139. if status = inst.Session().EvaluateRateLimit(now, 1); status == wire.RateLimitStatusDisconnect {
  140. break
  141. }
  142. }
  143. require.Equal(t, wire.RateLimitStatusDisconnect, status)
  144. require.True(t, inst.IsClosed(), "disconnect must close the OSCAR instance")
  145. // The aimsid no longer resolves, even though ExpiresAt is far in the future.
  146. _, err = mgr.GetSession(context.Background(), sess.AimSID)
  147. assert.ErrorIs(t, err, ErrWebAPISessionExpired)
  148. assert.False(t, sess.IsExpired(), "the guard must fire on OSCAR close, not on time expiry")
  149. // The reaper frees the dead entry on its next sweep.
  150. mgr.reapExpired()
  151. assert.NotContains(t, mgr.sessions, sess.AimSID)
  152. }
  153. // TestSessionManager_ShutdownDrainsAndClosesSessions verifies that Shutdown
  154. // collects every live session and tears it down: it drains the maps and closes
  155. // each session's event queue and OSCAR instance.
  156. func TestSessionManager_ShutdownDrainsAndClosesSessions(t *testing.T) {
  157. mgr := NewSessionManager()
  158. ctx := context.Background()
  159. inst1 := state.NewSession().AddInstance()
  160. inst2 := state.NewSession().AddInstance()
  161. s1, err := mgr.CreateSession(state.DisplayScreenName("alice"), []string{"presence"}, inst1, "", slog.Default())
  162. assert.NoError(t, err)
  163. s2, err := mgr.CreateSession(state.DisplayScreenName("bob"), []string{"presence"}, inst2, "", slog.Default())
  164. assert.NoError(t, err)
  165. assert.NoError(t, mgr.Shutdown(context.Background()))
  166. // Maps drained: the collect loop ran over both sessions.
  167. assert.Empty(t, mgr.sessions)
  168. // Each session's event queue and OSCAR instance were closed: the teardown
  169. // loop ran for every collected session.
  170. for _, s := range []*Session{s1, s2} {
  171. assertQueueClosed(t, ctx, s)
  172. }
  173. for _, inst := range []*state.SessionInstance{inst1, inst2} {
  174. select {
  175. case <-inst.Closed():
  176. default:
  177. t.Error("OSCAR instance should be closed")
  178. }
  179. }
  180. }
  181. // TestSessionManager_ReapExpired verifies reapExpired removes and tears
  182. // down only expired sessions, leaving live ones untouched.
  183. func TestSessionManager_ReapExpired(t *testing.T) {
  184. mgr := NewSessionManager()
  185. ctx := context.Background()
  186. expiredInst := state.NewSession().AddInstance()
  187. liveInst := state.NewSession().AddInstance()
  188. expired, err := mgr.CreateSession("alice", []string{"presence"}, expiredInst, "", slog.Default())
  189. assert.NoError(t, err)
  190. live, err := mgr.CreateSession("bob", []string{"presence"}, liveInst, "", slog.Default())
  191. assert.NoError(t, err)
  192. // Force alice's session into the past; bob keeps its default future expiry.
  193. expired.ExpiresAt = time.Now().Add(-time.Minute)
  194. mgr.reapExpired()
  195. // Expired session removed; live session retained.
  196. assert.NotContains(t, mgr.sessions, expired.AimSID)
  197. assert.Contains(t, mgr.sessions, live.AimSID)
  198. // Expired session torn down: event queue and OSCAR instance closed.
  199. assertQueueClosed(t, ctx, expired)
  200. select {
  201. case <-expiredInst.Closed():
  202. default:
  203. t.Error("expired session's OSCAR instance should be closed")
  204. }
  205. // Live session left running.
  206. select {
  207. case <-liveInst.Closed():
  208. t.Error("live session's OSCAR instance should not be closed")
  209. default:
  210. }
  211. }
  212. // assertQueueClosed asserts the session's event queue is closed: a fetch returns
  213. // straight away with no events and no error, rather than parking for the timeout.
  214. func assertQueueClosed(t *testing.T, ctx context.Context, sess *Session) {
  215. t.Helper()
  216. const timeout = 5 * time.Second
  217. start := time.Now()
  218. events, err := sess.EventQueue.Fetch(ctx, 0, timeout)
  219. assert.NoError(t, err)
  220. assert.Empty(t, events)
  221. assert.Less(t, time.Since(start), timeout/2, "fetch parked instead of returning on a closed queue")
  222. }
  223. // TestSessionManager_ShutdownWithoutReaper verifies Shutdown returns when no
  224. // reaper was ever started. Shutdown must not depend on the caller cancelling the
  225. // context passed to Run.
  226. func TestSessionManager_ShutdownWithoutReaper(t *testing.T) {
  227. mgr := NewSessionManager()
  228. done := make(chan struct{})
  229. go func() {
  230. defer close(done)
  231. // This test is about Shutdown returning at all, not what it returns.
  232. _ = mgr.Shutdown(context.Background())
  233. }()
  234. select {
  235. case <-done:
  236. case <-time.After(5 * time.Second):
  237. t.Fatal("Shutdown hung waiting for a reaper that was never started")
  238. }
  239. }
  240. // TestSessionManager_ShutdownJoinsReaper verifies Shutdown stops a running
  241. // reaper on its own and does not return until that reaper has exited.
  242. func TestSessionManager_ShutdownJoinsReaper(t *testing.T) {
  243. mgr := NewSessionManager()
  244. reaperExited := make(chan struct{})
  245. go func() {
  246. defer close(reaperExited)
  247. mgr.Run(context.Background()) // context is never cancelled: Shutdown must stop it
  248. }()
  249. // Give Run a chance to register itself before shutting down.
  250. time.Sleep(50 * time.Millisecond)
  251. done := make(chan struct{})
  252. go func() {
  253. defer close(done)
  254. // This test is about Shutdown returning at all, not what it returns.
  255. _ = mgr.Shutdown(context.Background())
  256. }()
  257. select {
  258. case <-done:
  259. case <-time.After(5 * time.Second):
  260. t.Fatal("Shutdown hung instead of stopping the reaper")
  261. }
  262. // Shutdown joins the reaper, so it has already exited by the time it returns.
  263. select {
  264. case <-reaperExited:
  265. default:
  266. t.Error("Shutdown returned before the reaper exited")
  267. }
  268. }
  269. // TestSessionManager_RunAfterShutdown verifies a reaper that loses the race
  270. // with Shutdown never starts, so it cannot reap an already-drained manager.
  271. func TestSessionManager_RunAfterShutdown(t *testing.T) {
  272. mgr := NewSessionManager()
  273. assert.NoError(t, mgr.Shutdown(context.Background()))
  274. done := make(chan struct{})
  275. go func() {
  276. defer close(done)
  277. mgr.Run(context.Background())
  278. }()
  279. select {
  280. case <-done:
  281. case <-time.After(5 * time.Second):
  282. t.Fatal("Run should be a no-op on a closed manager")
  283. }
  284. }
  285. // The client deletes the alias it holds each time it merges a user map, so every
  286. // event naming a buddy has to repeat it. An incoming IM and a presence change both
  287. // carry a user map, and both would otherwise rename an aliased buddy.
  288. func TestSession_UINBuddyReportsICQOnArrivalAndDeparture(t *testing.T) {
  289. sess := &Session{
  290. ScreenName: state.DisplayScreenName("me"),
  291. Events: []string{"presence"},
  292. EventQueue: NewEventQueue(10),
  293. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  294. }
  295. sess.handleBuddyArrived(wire.SNACMessage{Body: wire.SNAC_0x03_0x0B_BuddyArrived{
  296. TLVUserInfo: wire.TLVUserInfo{ScreenName: "100003"},
  297. }})
  298. sess.handleBuddyDeparted(wire.SNACMessage{Body: wire.SNAC_0x03_0x0C_BuddyDeparted{
  299. TLVUserInfo: wire.TLVUserInfo{ScreenName: "100003"},
  300. }})
  301. events := sess.EventQueue.GetAllEvents()
  302. require.Len(t, events, 2)
  303. assert.Equal(t, "icq", events[0].Data.(PresenceEvent).UserType)
  304. assert.Equal(t, "icq", events[1].Data.(PresenceEvent).UserType)
  305. }
  306. func TestSession_RepeatsBuddyAliasOnOSCAREvents(t *testing.T) {
  307. newSession := func() *Session {
  308. return &Session{
  309. ScreenName: state.DisplayScreenName("me"),
  310. Events: []string{"im", "conversation", "presence"},
  311. EventQueue: NewEventQueue(10),
  312. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  313. BuddyAliasLoader: func(_ context.Context) (map[string]string, error) {
  314. return map[string]string{"mikekelly": "MICHAELKELLY"}, nil
  315. },
  316. }
  317. }
  318. t.Run("incoming IM", func(t *testing.T) {
  319. sess := newSession()
  320. frags, err := wire.ICBMFragmentList("hello")
  321. require.NoError(t, err)
  322. body := wire.SNAC_0x04_0x07_ICBMChannelMsgToClient{
  323. ChannelID: wire.ICBMChannelIM,
  324. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  325. }
  326. body.Append(wire.NewTLVBE(wire.ICBMTLVAOLIMData, frags))
  327. sess.handleIncomingIM(wire.SNACMessage{Body: body})
  328. events := sess.EventQueue.GetAllEvents()
  329. require.NotEmpty(t, events)
  330. imEvent := events[0].Data.(IMEvent)
  331. assert.Equal(t, "mikekelly", imEvent.Source.AimID)
  332. assert.Equal(t, "Mike Kelly", imEvent.Source.DisplayID)
  333. assert.Equal(t, "MICHAELKELLY", imEvent.Source.Friendly)
  334. })
  335. t.Run("buddy arrived", func(t *testing.T) {
  336. sess := newSession()
  337. sess.handleBuddyArrived(wire.SNACMessage{Body: wire.SNAC_0x03_0x0B_BuddyArrived{
  338. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  339. }})
  340. events := sess.EventQueue.GetAllEvents()
  341. require.Len(t, events, 1)
  342. presence := events[0].Data.(PresenceEvent)
  343. assert.Equal(t, "mikekelly", presence.AimID)
  344. assert.Equal(t, "MICHAELKELLY", presence.Friendly)
  345. })
  346. t.Run("buddy departed", func(t *testing.T) {
  347. sess := newSession()
  348. sess.handleBuddyDeparted(wire.SNACMessage{Body: wire.SNAC_0x03_0x0C_BuddyDeparted{
  349. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  350. }})
  351. events := sess.EventQueue.GetAllEvents()
  352. require.Len(t, events, 1)
  353. presence := events[0].Data.(PresenceEvent)
  354. assert.Equal(t, "mikekelly", presence.AimID)
  355. assert.Equal(t, "MICHAELKELLY", presence.Friendly)
  356. })
  357. t.Run("unaliased buddy omits friendly", func(t *testing.T) {
  358. sess := newSession()
  359. sess.handleBuddyArrived(wire.SNACMessage{Body: wire.SNAC_0x03_0x0B_BuddyArrived{
  360. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Someone Else"},
  361. }})
  362. events := sess.EventQueue.GetAllEvents()
  363. require.Len(t, events, 1)
  364. assert.Empty(t, events[0].Data.(PresenceEvent).Friendly)
  365. })
  366. }
  367. // Aliases all come from one feedbag query, so a signon that brings a whole buddy
  368. // list online must not re-query the feedbag per buddy.
  369. func TestSession_CachesBuddyAliases(t *testing.T) {
  370. var loads int
  371. sess := &Session{
  372. ScreenName: state.DisplayScreenName("me"),
  373. Events: []string{"presence"},
  374. EventQueue: NewEventQueue(10),
  375. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  376. BuddyAliasLoader: func(_ context.Context) (map[string]string, error) {
  377. loads++
  378. return map[string]string{"mikekelly": "MICHAELKELLY"}, nil
  379. },
  380. }
  381. for range 5 {
  382. sess.handleBuddyArrived(wire.SNACMessage{Body: wire.SNAC_0x03_0x0B_BuddyArrived{
  383. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  384. }})
  385. }
  386. events := sess.EventQueue.GetAllEvents()
  387. require.Len(t, events, 5)
  388. for _, event := range events {
  389. assert.Equal(t, "MICHAELKELLY", event.Data.(PresenceEvent).Friendly)
  390. }
  391. assert.Equal(t, 1, loads, "aliases should be loaded once, not once per event")
  392. }
  393. // A feedbag change from another of the owner's clients arrives as a SNAC, which is
  394. // the session's only signal that its cached aliases are stale.
  395. func TestSession_FeedbagSNACInvalidatesAliasCache(t *testing.T) {
  396. alias := "MICHAELKELLY"
  397. sess := &Session{
  398. ScreenName: state.DisplayScreenName("me"),
  399. Events: []string{"presence"},
  400. EventQueue: NewEventQueue(10),
  401. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  402. BuddyAliasLoader: func(_ context.Context) (map[string]string, error) {
  403. return map[string]string{"mikekelly": alias}, nil
  404. },
  405. }
  406. arrive := func() PresenceEvent {
  407. sess.handleBuddyArrived(wire.SNACMessage{Body: wire.SNAC_0x03_0x0B_BuddyArrived{
  408. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  409. }})
  410. events := sess.EventQueue.GetAllEvents()
  411. require.NotEmpty(t, events)
  412. return events[len(events)-1].Data.(PresenceEvent)
  413. }
  414. assert.Equal(t, "MICHAELKELLY", arrive().Friendly)
  415. // The buddy is renamed elsewhere: the feedbag SNAC must drop the cached map.
  416. alias = "MIKE"
  417. sess.handleFeedbagMessage(wire.SNACMessage{
  418. Frame: wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagUpdateItem},
  419. Body: wire.SNAC_0x13_0x09_FeedbagUpdateItem{},
  420. })
  421. assert.Equal(t, "MIKE", arrive().Friendly)
  422. }
  423. // Permit/deny changes from another of the owner's clients arrive as an insert,
  424. // an update, or a delete, and all three have to refresh the client's privacy
  425. // state.
  426. func TestSession_FeedbagSNACRefreshesPermitDeny(t *testing.T) {
  427. denyItem := wire.FeedbagItem{ClassID: wire.FeedbagClassIDDeny, Name: "blockeduser"}
  428. buddyItem := wire.FeedbagItem{ClassID: wire.FeedbagClassIdBuddy, Name: "friend"}
  429. tests := []struct {
  430. name string
  431. subGroup uint16
  432. body any
  433. wantEvent bool
  434. }{
  435. {
  436. name: "insert relays an update body",
  437. subGroup: wire.FeedbagInsertItem,
  438. body: wire.SNAC_0x13_0x09_FeedbagUpdateItem{Items: []wire.FeedbagItem{denyItem}},
  439. wantEvent: true,
  440. },
  441. {
  442. name: "update",
  443. subGroup: wire.FeedbagUpdateItem,
  444. body: wire.SNAC_0x13_0x09_FeedbagUpdateItem{Items: []wire.FeedbagItem{denyItem}},
  445. wantEvent: true,
  446. },
  447. {
  448. name: "delete",
  449. subGroup: wire.FeedbagDeleteItem,
  450. body: wire.SNAC_0x13_0x0A_FeedbagDeleteItem{Items: []wire.FeedbagItem{denyItem}},
  451. wantEvent: true,
  452. },
  453. {
  454. name: "buddy item only",
  455. subGroup: wire.FeedbagInsertItem,
  456. body: wire.SNAC_0x13_0x09_FeedbagUpdateItem{Items: []wire.FeedbagItem{buddyItem}},
  457. wantEvent: false,
  458. },
  459. }
  460. for _, tt := range tests {
  461. t.Run(tt.name, func(t *testing.T) {
  462. sess := &Session{
  463. ScreenName: state.DisplayScreenName("me"),
  464. EventQueue: NewEventQueue(10),
  465. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  466. PermitDenyRefresher: func(_ context.Context) (any, error) {
  467. return map[string]any{"pdMode": "denySome"}, nil
  468. },
  469. }
  470. sess.handleFeedbagMessage(wire.SNACMessage{
  471. Frame: wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: tt.subGroup},
  472. Body: tt.body,
  473. })
  474. var got int
  475. for _, event := range sess.EventQueue.GetAllEvents() {
  476. if event.Type == EventTypePermitDeny {
  477. got++
  478. }
  479. }
  480. if tt.wantEvent {
  481. assert.Equal(t, 1, got)
  482. } else {
  483. assert.Zero(t, got)
  484. }
  485. })
  486. }
  487. }
  488. // A session sees no SNAC for feedbag writes it makes itself, so the handlers that
  489. // perform those writes invalidate the cache directly.
  490. func TestSession_InvalidateAliases(t *testing.T) {
  491. alias := "MICHAELKELLY"
  492. sess := &Session{
  493. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  494. BuddyAliasLoader: func(_ context.Context) (map[string]string, error) {
  495. return map[string]string{"mikekelly": alias}, nil
  496. },
  497. }
  498. assert.Equal(t, "MICHAELKELLY", sess.Aliases(context.Background())["mikekelly"])
  499. alias = "MIKE"
  500. assert.Equal(t, "MICHAELKELLY", sess.Aliases(context.Background())["mikekelly"], "cached until invalidated")
  501. sess.InvalidateAliases()
  502. assert.Equal(t, "MIKE", sess.Aliases(context.Background())["mikekelly"])
  503. }
  504. // A failed load must not be cached as an empty map: aliases would stay missing for
  505. // the life of the session.
  506. func TestSession_AliasLoadErrorIsNotCached(t *testing.T) {
  507. var loads int
  508. sess := &Session{
  509. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  510. BuddyAliasLoader: func(_ context.Context) (map[string]string, error) {
  511. loads++
  512. if loads == 1 {
  513. return nil, io.EOF
  514. }
  515. return map[string]string{"mikekelly": "MICHAELKELLY"}, nil
  516. },
  517. }
  518. assert.Empty(t, sess.Aliases(context.Background()))
  519. assert.Equal(t, "MICHAELKELLY", sess.Aliases(context.Background())["mikekelly"])
  520. }
  521. func TestSession_HandleIncomingIM_NormalizesAimID(t *testing.T) {
  522. sess := &Session{
  523. ScreenName: state.DisplayScreenName("me"),
  524. Events: []string{"im", "conversation"},
  525. EventQueue: NewEventQueue(10),
  526. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  527. }
  528. frags, err := wire.ICBMFragmentList("hello")
  529. assert.NoError(t, err)
  530. body := wire.SNAC_0x04_0x07_ICBMChannelMsgToClient{
  531. ChannelID: wire.ICBMChannelIM,
  532. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  533. }
  534. body.Append(wire.NewTLVBE(wire.ICBMTLVAOLIMData, frags))
  535. sess.handleIncomingIM(wire.SNACMessage{Body: body})
  536. events := sess.EventQueue.GetAllEvents()
  537. require.Len(t, events, 2)
  538. imEvent := events[0].Data.(IMEvent)
  539. assert.Equal(t, "mikekelly", imEvent.Source.AimID)
  540. assert.Equal(t, "Mike Kelly", imEvent.Source.DisplayID)
  541. convData := events[1].Data.(*ConversationData)
  542. require.Len(t, convData.Conversations, 1)
  543. entry := convData.Conversations[0]
  544. assert.Equal(t, "mikekelly", entry.AimID)
  545. assert.Equal(t, "Mike Kelly", entry.DisplayID)
  546. require.NotNil(t, entry.LastIM)
  547. assert.Equal(t, "mikekelly", entry.LastIM.Sender)
  548. // The IM log is keyed by aimId, so the conversation the client opens from
  549. // this event finds its own history.
  550. msgs := sess.GetStoredIMs(StoredIMQuery{PartnerAimID: "mikekelly", NToGet: 10})
  551. require.Len(t, msgs, 1)
  552. assert.Equal(t, "hello", msgs[0].Message)
  553. }
  554. func TestSession_HandleTypingNotification_NormalizesAimID(t *testing.T) {
  555. sess := &Session{
  556. Events: []string{"typing"},
  557. EventQueue: NewEventQueue(10),
  558. }
  559. sess.handleTypingNotification(wire.SNACMessage{
  560. Body: wire.SNAC_0x04_0x14_ICBMClientEvent{
  561. ScreenName: "Mike Kelly",
  562. Event: 0x0002,
  563. },
  564. })
  565. events := sess.EventQueue.GetAllEvents()
  566. require.Len(t, events, 1)
  567. typing := events[0].Data.(TypingEvent)
  568. assert.Equal(t, "mikekelly", typing.AimID)
  569. assert.Equal(t, "typing", typing.TypingStatus)
  570. }
  571. func TestSession_HandleBuddyArrivedDeparted_NormalizesAimID(t *testing.T) {
  572. sess := &Session{
  573. Events: []string{"presence"},
  574. EventQueue: NewEventQueue(10),
  575. }
  576. sess.handleBuddyArrived(wire.SNACMessage{
  577. Body: wire.SNAC_0x03_0x0B_BuddyArrived{
  578. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  579. },
  580. })
  581. sess.handleBuddyDeparted(wire.SNACMessage{
  582. Body: wire.SNAC_0x03_0x0C_BuddyDeparted{
  583. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  584. },
  585. })
  586. events := sess.EventQueue.GetAllEvents()
  587. require.Len(t, events, 2)
  588. arrived := events[0].Data.(PresenceEvent)
  589. assert.Equal(t, "mikekelly", arrived.AimID)
  590. assert.Equal(t, "online", arrived.State)
  591. departed := events[1].Data.(PresenceEvent)
  592. assert.Equal(t, "mikekelly", departed.AimID)
  593. assert.Equal(t, "offline", departed.State)
  594. }
  595. // A BuddyArrived carries the buddy's current icon as TLV 0x1D, so an icon change
  596. // rides along on the presence broadcast and must reach the presence event. The
  597. // stub BuddyIconURL stands in for the handlers-side URL formatter, which state
  598. // cannot import.
  599. func TestSession_PublishesBuddyIconOnPresence(t *testing.T) {
  600. newSession := func() *Session {
  601. return &Session{
  602. ScreenName: state.DisplayScreenName("me"),
  603. Events: []string{"presence"},
  604. EventQueue: NewEventQueue(10),
  605. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  606. BuddyIconURL: func(sn state.IdentScreenName, hash []byte) string {
  607. if len(hash) == 0 {
  608. return "placeholder:" + sn.String()
  609. }
  610. return "icon:" + hex.EncodeToString(hash)
  611. },
  612. }
  613. }
  614. arrived := func(sess *Session, screenName string, hash []byte) {
  615. info := wire.TLVUserInfo{ScreenName: screenName}
  616. if hash != nil {
  617. info.Append(wire.NewTLVBE(wire.OServiceUserInfoBARTInfo, wire.BARTID{
  618. Type: wire.BARTTypesBuddyIcon,
  619. BARTInfo: wire.BARTInfo{Hash: hash},
  620. }))
  621. }
  622. sess.handleBuddyArrived(wire.SNACMessage{Body: wire.SNAC_0x03_0x0B_BuddyArrived{TLVUserInfo: info}})
  623. }
  624. lastPresence := func(sess *Session) PresenceEvent {
  625. events := sess.EventQueue.GetAllEvents()
  626. require.Len(t, events, 1)
  627. return events[0].Data.(PresenceEvent)
  628. }
  629. t.Run("icon hash yields the content-addressed URL", func(t *testing.T) {
  630. sess := newSession()
  631. arrived(sess, "Mike Kelly", []byte{0xde, 0xad, 0xbe, 0xef})
  632. assert.Equal(t, "icon:deadbeef", lastPresence(sess).BuddyIcon)
  633. })
  634. t.Run("no icon TLV yields the placeholder URL", func(t *testing.T) {
  635. sess := newSession()
  636. arrived(sess, "Mike Kelly", nil)
  637. assert.Equal(t, "placeholder:mikekelly", lastPresence(sess).BuddyIcon)
  638. })
  639. t.Run("cleared icon yields a URL naming the sentinel hash", func(t *testing.T) {
  640. sess := newSession()
  641. arrived(sess, "Mike Kelly", wire.GetClearIconHash())
  642. assert.Equal(t, "icon:"+hex.EncodeToString(wire.GetClearIconHash()), lastPresence(sess).BuddyIcon)
  643. })
  644. t.Run("departed omits the icon so the client preserves it", func(t *testing.T) {
  645. sess := newSession()
  646. sess.handleBuddyDeparted(wire.SNACMessage{Body: wire.SNAC_0x03_0x0C_BuddyDeparted{
  647. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  648. }})
  649. assert.Empty(t, lastPresence(sess).BuddyIcon)
  650. })
  651. t.Run("no callback wired omits the icon", func(t *testing.T) {
  652. sess := newSession()
  653. sess.BuddyIconURL = nil
  654. arrived(sess, "Mike Kelly", []byte{0x01})
  655. assert.Empty(t, lastPresence(sess).BuddyIcon)
  656. })
  657. }
  658. // A user's own icon change is relayed to their session as OServiceUserInfoUpdate,
  659. // which the pump turns into a myInfo event so the identity badge re-renders.
  660. func TestSession_PushesMyInfoOnUserInfoUpdate(t *testing.T) {
  661. newSession := func(events ...string) (*Session, *int) {
  662. var refreshes int
  663. return &Session{
  664. ScreenName: state.DisplayScreenName("me"),
  665. Events: events,
  666. EventQueue: NewEventQueue(10),
  667. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  668. MyInfoRefresher: func(_ context.Context) (any, error) {
  669. refreshes++
  670. return map[string]any{"aimId": "me", "buddyIcon": "icon:new"}, nil
  671. },
  672. }, &refreshes
  673. }
  674. userInfoUpdate := wire.SNACMessage{Frame: wire.SNACFrame{
  675. FoodGroup: wire.OService,
  676. SubGroup: wire.OServiceUserInfoUpdate,
  677. }}
  678. t.Run("subscribed session gets one myInfo event", func(t *testing.T) {
  679. sess, refreshes := newSession("myInfo")
  680. sess.handleSNACMessage(userInfoUpdate)
  681. events := sess.EventQueue.GetAllEvents()
  682. require.Len(t, events, 1)
  683. assert.Equal(t, "myInfo", string(events[0].Type))
  684. assert.Equal(t, "icon:new", events[0].Data.(map[string]any)["buddyIcon"])
  685. assert.Equal(t, 1, *refreshes)
  686. })
  687. t.Run("a presence subscription also delivers myInfo", func(t *testing.T) {
  688. sess, _ := newSession("presence")
  689. sess.handleSNACMessage(userInfoUpdate)
  690. assert.Len(t, sess.EventQueue.GetAllEvents(), 1)
  691. })
  692. t.Run("unsubscribed session gets nothing and does not refresh", func(t *testing.T) {
  693. sess, refreshes := newSession("im")
  694. sess.handleSNACMessage(userInfoUpdate)
  695. assert.Empty(t, sess.EventQueue.GetAllEvents())
  696. assert.Equal(t, 0, *refreshes)
  697. })
  698. t.Run("other OService subgroups are ignored", func(t *testing.T) {
  699. sess, refreshes := newSession("myInfo")
  700. sess.handleSNACMessage(wire.SNACMessage{Frame: wire.SNACFrame{
  701. FoodGroup: wire.OService,
  702. SubGroup: wire.OServiceRateParamsQuery,
  703. }})
  704. assert.Empty(t, sess.EventQueue.GetAllEvents())
  705. assert.Equal(t, 0, *refreshes)
  706. })
  707. }
  708. // TestSessionManager_ShutdownBoundedByContext verifies that Shutdown
  709. // honors its context instead of blocking indefinitely. A listener goroutine that
  710. // ignores cancellation must not be able to hold the whole server open: main
  711. // budgets a few seconds for every server's shutdown combined, so an unbounded
  712. // wait here means the process never exits.
  713. func TestSessionManager_ShutdownBoundedByContext(t *testing.T) {
  714. mgr := NewSessionManager()
  715. inst := state.NewSession().AddInstance()
  716. sess, err := mgr.CreateSession("alice", []string{"presence"}, inst, "", slog.Default())
  717. assert.NoError(t, err)
  718. // Stand in for a listener wedged somewhere that never observes cancellation.
  719. release := make(chan struct{})
  720. defer close(release)
  721. sess.listeners.Go(func() {
  722. <-release
  723. })
  724. ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
  725. defer cancel()
  726. start := time.Now()
  727. err = mgr.Shutdown(ctx)
  728. elapsed := time.Since(start)
  729. assert.ErrorIs(t, err, context.DeadlineExceeded)
  730. assert.Less(t, elapsed, 2*time.Second, "Shutdown must give up at its deadline, not wait on the stuck listener")
  731. }
  732. // TestSession_CloseCancelsSessionContext verifies that Close cancels the
  733. // context handed to the refresher callbacks. The listener runs feedbag queries
  734. // through it, and without cancellation Close's wait lasts as long as the query.
  735. func TestSession_CloseCancelsSessionContext(t *testing.T) {
  736. mgr := NewSessionManager()
  737. inst := state.NewSession().AddInstance()
  738. sess, err := mgr.CreateSession("alice", []string{"presence"}, inst, "", slog.Default())
  739. assert.NoError(t, err)
  740. assert.NoError(t, sess.ctx.Err(), "session context should be live before Close")
  741. sess.Close()
  742. assert.ErrorIs(t, sess.ctx.Err(), context.Canceled)
  743. }
  744. // A message replayed out of the offline store arrives as an ordinary
  745. // ICBMChannelMsgToClient stamped with a send time. The client models that as its
  746. // own offlineIM event, keyed by a bare aimId and timestamped when the sender sent
  747. // it rather than when it was delivered.
  748. func TestSession_OfflineIM(t *testing.T) {
  749. sentAt := time.Now().Add(-2 * time.Hour).Unix()
  750. newSession := func(events ...string) *Session {
  751. return &Session{
  752. ScreenName: state.DisplayScreenName("me"),
  753. Events: events,
  754. EventQueue: NewEventQueue(10),
  755. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  756. }
  757. }
  758. storedMsg := func(t *testing.T, withSendTime bool) wire.SNACMessage {
  759. t.Helper()
  760. frags, err := wire.ICBMFragmentList("sent while you were out")
  761. require.NoError(t, err)
  762. body := wire.SNAC_0x04_0x07_ICBMChannelMsgToClient{
  763. ChannelID: wire.ICBMChannelIM,
  764. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  765. }
  766. body.Append(wire.NewTLVBE(wire.ICBMTLVAOLIMData, frags))
  767. if withSendTime {
  768. body.Append(wire.NewTLVBE(wire.ICBMTLVSendTime, uint32(sentAt)))
  769. }
  770. return wire.SNACMessage{Body: body}
  771. }
  772. t.Run("send time yields an offlineIM event", func(t *testing.T) {
  773. sess := newSession("im", "offlineIM")
  774. sess.handleIncomingIM(storedMsg(t, true))
  775. events := sess.EventQueue.GetAllEvents()
  776. require.Len(t, events, 1)
  777. assert.Equal(t, EventTypeOfflineIM, events[0].Type)
  778. offline := events[0].Data.(OfflineIMEvent)
  779. assert.Equal(t, "mikekelly", offline.AimID)
  780. assert.Equal(t, "sent while you were out", offline.Message)
  781. assert.NotEmpty(t, offline.MsgID)
  782. assert.Equal(t, int64(sentAt), offline.Timestamp)
  783. })
  784. t.Run("no send time yields an im event", func(t *testing.T) {
  785. sess := newSession("im", "offlineIM")
  786. sess.handleIncomingIM(storedMsg(t, false))
  787. events := sess.EventQueue.GetAllEvents()
  788. require.Len(t, events, 1)
  789. assert.Equal(t, EventTypeIM, events[0].Type)
  790. })
  791. t.Run("offlineIM subscriber gets a conversation update", func(t *testing.T) {
  792. sess := newSession("offlineIM", "conversation")
  793. sess.handleIncomingIM(storedMsg(t, true))
  794. events := sess.EventQueue.GetAllEvents()
  795. require.Len(t, events, 2)
  796. assert.Equal(t, EventTypeOfflineIM, events[0].Type)
  797. assert.Equal(t, EventTypeConversation, events[1].Type)
  798. })
  799. // The history the client pulls with fetchStoredIMs has to order the message by
  800. // when it was sent, not when the session that drained the store started.
  801. t.Run("logs the message under its send time", func(t *testing.T) {
  802. sess := newSession("offlineIM")
  803. sess.handleIncomingIM(storedMsg(t, true))
  804. stored := sess.GetStoredIMs(StoredIMQuery{PartnerAimID: "mikekelly", NToGet: 10})
  805. require.Len(t, stored, 1)
  806. assert.Equal(t, int64(sentAt), stored[0].Date)
  807. })
  808. // Only a live IM is filtered on subscription here. Retrieval answers the
  809. // instance that asked and StartSession asks only for an offlineIM subscriber,
  810. // so a stamped message reaching a session that did not subscribe is not a state
  811. // this handler can be put in.
  812. t.Run("no subscription drops a live message", func(t *testing.T) {
  813. sess := newSession("presence")
  814. sess.handleIncomingIM(storedMsg(t, false))
  815. assert.Empty(t, sess.EventQueue.GetAllEvents())
  816. })
  817. }
  818. // A boot closes the account's OSCAR session out from under its web session. The
  819. // client is parked on a long poll at that moment, so it must be released with a
  820. // sessionEnded event rather than left to hang until the reaper's next sweep —
  821. // which measured 26-28s against a running server.
  822. func TestSession_BootReleasesParkedFetcherWithSessionEnded(t *testing.T) {
  823. mgr := NewSessionManager()
  824. inst := state.NewSession().AddInstance()
  825. sess, err := mgr.CreateSession(state.DisplayScreenName("mike"), []string{"presence"}, inst, "", slog.Default())
  826. require.NoError(t, err)
  827. sess.StartListeningToOSCARSession()
  828. // Park a fetcher the way fetchEvents does, with nothing pending.
  829. type result struct {
  830. events []Event
  831. err error
  832. }
  833. done := make(chan result, 1)
  834. go func() {
  835. events, err := sess.EventQueue.Fetch(context.Background(), 0, 60*time.Second)
  836. done <- result{events, err}
  837. }()
  838. // Let the fetcher block before the session is taken away.
  839. time.Sleep(50 * time.Millisecond)
  840. inst.Session().CloseSession()
  841. select {
  842. case got := <-done:
  843. require.NoError(t, got.err)
  844. require.Len(t, got.events, 1)
  845. assert.Equal(t, EventTypeSessionEnded, got.events[0].Type)
  846. case <-time.After(5 * time.Second):
  847. t.Fatal("parked fetcher was not released by the boot")
  848. }
  849. }
  850. // A session tearing itself down — endSession, or the idle reaper — needs no
  851. // sessionEnded event: the client already knows it is leaving. Close closes the
  852. // queue before the instance, so the listener's push lands on a closed queue.
  853. func TestSession_SelfCloseEmitsNoSessionEndedEvent(t *testing.T) {
  854. mgr := NewSessionManager()
  855. inst := state.NewSession().AddInstance()
  856. sess, err := mgr.CreateSession(state.DisplayScreenName("mike"), []string{"presence"}, inst, "", slog.Default())
  857. require.NoError(t, err)
  858. sess.StartListeningToOSCARSession()
  859. require.NoError(t, mgr.RemoveSession(context.Background(), sess.AimSID))
  860. events, err := sess.EventQueue.Fetch(context.Background(), 0, time.Second)
  861. require.NoError(t, err)
  862. assert.Empty(t, events)
  863. }
  864. func TestSession_GetStoredIMs(t *testing.T) {
  865. sess := &Session{}
  866. sess.AddStoredIM("buddy1", "me", "hello", "msg-1", 100)
  867. sess.AddStoredIM("buddy1", "buddy1", "hi back", "msg-2", 200)
  868. sess.AddStoredIM("buddy2", "buddy2", "other chat", "msg-3", 150)
  869. msgs := sess.GetStoredIMs(StoredIMQuery{
  870. PartnerAimID: "buddy1",
  871. SortOrder: "descendingDate",
  872. NToGet: 10,
  873. })
  874. assert.Len(t, msgs, 2)
  875. assert.Equal(t, "msg-2", msgs[0].MsgID)
  876. assert.Equal(t, int64(200), msgs[0].Date)
  877. assert.Equal(t, "hello", msgs[1].Message)
  878. msgs = sess.GetStoredIMs(StoredIMQuery{
  879. PartnerAimID: "buddy1",
  880. SortOrder: "ascendingDate",
  881. StartTime: 150,
  882. EndTime: 250,
  883. })
  884. assert.Len(t, msgs, 1)
  885. assert.Equal(t, "msg-2", msgs[0].MsgID)
  886. }
  887. func TestSession_GetStoredIMs_NormalizesPartner(t *testing.T) {
  888. sess := &Session{}
  889. sess.AddStoredIM("Mike Kelly", "mikekelly", "hello", "msg-1", 100)
  890. // The web client queries history by the normalized aimId, never by the
  891. // display screen name it was stored under.
  892. msgs := sess.GetStoredIMs(StoredIMQuery{
  893. PartnerAimID: "mikekelly",
  894. NToGet: 10,
  895. })
  896. require.Len(t, msgs, 1)
  897. assert.Equal(t, "msg-1", msgs[0].MsgID)
  898. }
  899. // A session gets no insert/update/delete SNAC for a feedbag change it made itself —
  900. // those reach only a user's *other* instances. FeedbagStatus is the one notification
  901. // it does receive, so it drives the roster event for the client's own edits.
  902. func TestSession_FeedbagStatusRefreshesBuddyList(t *testing.T) {
  903. tests := []struct {
  904. name string
  905. events []string
  906. results []uint16
  907. body any
  908. wantEvent bool
  909. }{
  910. {
  911. name: "stored item refreshes the roster",
  912. events: []string{"buddylist"},
  913. results: []uint16{0x0000},
  914. wantEvent: true,
  915. },
  916. {
  917. // The declined item is still worth a refresh: the roster is how the
  918. // client discovers the buddy was not stored, since it is absent from it.
  919. name: "declined item still refreshes the roster",
  920. events: []string{"buddylist"},
  921. results: []uint16{feedbagResultAuthRequired},
  922. wantEvent: true,
  923. },
  924. {
  925. name: "no event when not subscribed",
  926. events: []string{"presence"},
  927. results: []uint16{0x0000},
  928. wantEvent: false,
  929. },
  930. {
  931. name: "a body of the wrong type still refreshes",
  932. events: []string{"buddylist"},
  933. body: wire.SNAC_0x13_0x06_FeedbagReply{},
  934. wantEvent: true,
  935. },
  936. }
  937. for _, tt := range tests {
  938. t.Run(tt.name, func(t *testing.T) {
  939. refreshed := 0
  940. sess := &Session{
  941. ScreenName: state.DisplayScreenName("me"),
  942. Events: tt.events,
  943. EventQueue: NewEventQueue(10),
  944. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  945. BuddyListRefresher: func(_ context.Context) (any, error) {
  946. refreshed++
  947. return &BuddyListData{Groups: []BuddyGroup{}}, nil
  948. },
  949. }
  950. body := tt.body
  951. if body == nil {
  952. body = wire.SNAC_0x13_0x0E_FeedbagStatus{Results: tt.results}
  953. }
  954. sess.handleFeedbagMessage(wire.SNACMessage{
  955. Frame: wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagStatus},
  956. Body: body,
  957. })
  958. var got int
  959. for _, event := range sess.EventQueue.GetAllEvents() {
  960. if event.Type == EventTypeBuddyList {
  961. got++
  962. }
  963. }
  964. if tt.wantEvent {
  965. assert.Equal(t, 1, got)
  966. assert.Equal(t, 1, refreshed)
  967. } else {
  968. assert.Zero(t, got)
  969. assert.Zero(t, refreshed, "an unsubscribed session should not even query the roster")
  970. }
  971. })
  972. }
  973. }
  974. func TestSession_HandleClientError(t *testing.T) {
  975. const (
  976. cookie = uint64(0xDEADBEEFCAFEF00D)
  977. msgID = "11112222-3333-4444-8000-555566667777"
  978. )
  979. tests := []struct {
  980. name string
  981. // events is what the session subscribed to at startSession.
  982. events []string
  983. // record seeds the cookie->msgId map the way a prior im/sendIM would.
  984. record bool
  985. channelID uint16
  986. wantEvent bool
  987. wantCooki string
  988. wantChan string
  989. }{
  990. {
  991. name: "im channel names the message this session sent",
  992. events: []string{"im"},
  993. record: true,
  994. channelID: wire.ICBMChannelIM,
  995. wantEvent: true,
  996. wantCooki: msgID,
  997. wantChan: "im",
  998. },
  999. {
  1000. name: "rendezvous channel is reported as data",
  1001. events: []string{"im"},
  1002. record: true,
  1003. channelID: wire.ICBMChannelRendezvous,
  1004. wantEvent: true,
  1005. wantCooki: msgID,
  1006. wantChan: "data",
  1007. },
  1008. {
  1009. // Another instance of the account sent the message, so this session
  1010. // has no msgId for it and must not invent one.
  1011. name: "unknown cookie yields an empty msgId",
  1012. events: []string{"im"},
  1013. record: false,
  1014. channelID: wire.ICBMChannelIM,
  1015. wantEvent: true,
  1016. wantCooki: "",
  1017. wantChan: "im",
  1018. },
  1019. {
  1020. name: "not subscribed to im",
  1021. events: []string{"presence"},
  1022. record: true,
  1023. channelID: wire.ICBMChannelIM,
  1024. wantEvent: false,
  1025. },
  1026. }
  1027. for _, tt := range tests {
  1028. t.Run(tt.name, func(t *testing.T) {
  1029. sess := &Session{
  1030. Events: tt.events,
  1031. EventQueue: NewEventQueue(10),
  1032. }
  1033. if tt.record {
  1034. sess.RecordSentIM(cookie, msgID)
  1035. }
  1036. sess.handleSNACMessage(wire.SNACMessage{
  1037. Frame: wire.SNACFrame{
  1038. FoodGroup: wire.ICBM,
  1039. SubGroup: wire.ICBMClientErr,
  1040. },
  1041. Body: wire.SNAC_0x04_0x0B_ICBMClientErr{
  1042. Cookie: cookie,
  1043. ChannelID: tt.channelID,
  1044. ScreenName: "Mike Kelly",
  1045. Code: 0x0004,
  1046. },
  1047. })
  1048. events := sess.EventQueue.GetAllEvents()
  1049. if !tt.wantEvent {
  1050. assert.Empty(t, events)
  1051. return
  1052. }
  1053. require.Len(t, events, 1)
  1054. assert.Equal(t, EventTypeClientError, events[0].Type)
  1055. got := events[0].Data.(ClientErrorEvent)
  1056. assert.Equal(t, tt.wantCooki, got.Cookie)
  1057. assert.Equal(t, tt.wantChan, got.Channel)
  1058. // The client keys users by the normalized id and renders the sender's
  1059. // own formatting, so both forms have to survive the translation.
  1060. assert.Equal(t, "mikekelly", got.Source.AimID)
  1061. assert.Equal(t, "Mike Kelly", got.Source.DisplayID)
  1062. })
  1063. }
  1064. }
  1065. func TestSession_RecordSentIMEvictsOldestCookie(t *testing.T) {
  1066. sess := &Session{}
  1067. for i := 0; i <= sentIMCookieLimit; i++ {
  1068. sess.RecordSentIM(uint64(i), fmt.Sprintf("msg-%d", i))
  1069. }
  1070. // The map is capped, so the oldest send is forgotten while the newest and the
  1071. // one that pushed the map over its limit are both still resolvable.
  1072. assert.Equal(t, "", sess.msgIDForCookie(0))
  1073. assert.Equal(t, "msg-1", sess.msgIDForCookie(1))
  1074. assert.Equal(t, fmt.Sprintf("msg-%d", sentIMCookieLimit), sess.msgIDForCookie(uint64(sentIMCookieLimit)))
  1075. assert.Len(t, sess.sentIMs, sentIMCookieLimit)
  1076. // A repeat cookie updates in place rather than consuming another slot.
  1077. sess.RecordSentIM(1, "msg-1-again")
  1078. assert.Equal(t, "msg-1-again", sess.msgIDForCookie(1))
  1079. assert.Len(t, sess.sentIMs, sentIMCookieLimit)
  1080. }
  1081. // A buddy's mood rides along in the capability list of a BuddyArrived, so the
  1082. // presence event has to carry it as a mood icon URL.
  1083. func TestSession_PublishesMoodOnPresence(t *testing.T) {
  1084. newSession := func() *Session {
  1085. return &Session{
  1086. ScreenName: state.DisplayScreenName("me"),
  1087. BaseURL: "http://host",
  1088. Events: []string{"presence"},
  1089. EventQueue: NewEventQueue(10),
  1090. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  1091. }
  1092. }
  1093. // arrived delivers a BuddyArrived carrying a raw capabilities TLV value.
  1094. arrived := func(sess *Session, caps []byte, invisible bool) PresenceEvent {
  1095. info := wire.TLVUserInfo{ScreenName: "Mike Kelly"}
  1096. if caps != nil {
  1097. info.Append(wire.NewTLVBE(wire.OServiceUserInfoOscarCaps, caps))
  1098. }
  1099. if invisible {
  1100. info.Append(wire.NewTLVBE(wire.OServiceUserInfoStatus, wire.OServiceUserStatusInvisible))
  1101. }
  1102. sess.handleBuddyArrived(wire.SNACMessage{Body: wire.SNAC_0x03_0x0B_BuddyArrived{TLVUserInfo: info}})
  1103. events := sess.EventQueue.GetAllEvents()
  1104. require.Len(t, events, 1)
  1105. return events[0].Data.(PresenceEvent)
  1106. }
  1107. capBytes := func(caps ...[16]byte) []byte {
  1108. var b []byte
  1109. for _, c := range caps {
  1110. b = append(b, c[:]...)
  1111. }
  1112. return b
  1113. }
  1114. t.Run("a mood capability yields the mood icon URL", func(t *testing.T) {
  1115. got := arrived(newSession(), capBytes(wire.CapXStatusBeer), false)
  1116. assert.Equal(t, "http://host/mood?id="+wire.MoodIconID("0icqmood4"), got.MoodIcon)
  1117. })
  1118. t.Run("a placeholder capability resolves too", func(t *testing.T) {
  1119. got := arrived(newSession(), capBytes(wire.CapMoodOnTheWay), false)
  1120. assert.Equal(t, "http://host/mood?id="+wire.MoodIconID("0icqmood83"), got.MoodIcon)
  1121. })
  1122. t.Run("a shared capability resolves to the canonical mood", func(t *testing.T) {
  1123. // Console is reachable from 0icqmood15 and 0icqmood81; the table's first
  1124. // entry wins, so the client is told the one it labels "gamepad".
  1125. got := arrived(newSession(), capBytes(wire.CapXStatusConsole), false)
  1126. assert.Equal(t, "http://host/mood?id="+wire.MoodIconID("0icqmood81"), got.MoodIcon)
  1127. })
  1128. t.Run("a mood is found after other capabilities", func(t *testing.T) {
  1129. got := arrived(newSession(), capBytes(wire.CapChat, wire.CapXStatusBeer), false)
  1130. assert.Equal(t, "http://host/mood?id="+wire.MoodIconID("0icqmood4"), got.MoodIcon)
  1131. })
  1132. t.Run("capabilities carrying no mood yield no icon", func(t *testing.T) {
  1133. assert.Empty(t, arrived(newSession(), capBytes(wire.CapChat), false).MoodIcon)
  1134. })
  1135. t.Run("no capabilities TLV yields no icon", func(t *testing.T) {
  1136. assert.Empty(t, arrived(newSession(), nil, false).MoodIcon)
  1137. })
  1138. t.Run("a trailing partial capability is ignored", func(t *testing.T) {
  1139. // A truncated final chunk must not be read as a capability, nor panic.
  1140. truncated := append(capBytes(wire.CapXStatusBeer), 0x01, 0x02, 0x03)
  1141. got := arrived(newSession(), truncated, false)
  1142. assert.Equal(t, "http://host/mood?id="+wire.MoodIconID("0icqmood4"), got.MoodIcon)
  1143. })
  1144. t.Run("a partial capability alone yields no icon", func(t *testing.T) {
  1145. assert.Empty(t, arrived(newSession(), []byte{0x01, 0x02, 0x03}, false).MoodIcon)
  1146. })
  1147. t.Run("an invisible buddy shows no mood", func(t *testing.T) {
  1148. // A mood supersedes state on the client, so one here would render the
  1149. // buddy as present instead of offline.
  1150. got := arrived(newSession(), capBytes(wire.CapXStatusBeer), true)
  1151. assert.Equal(t, "offline", got.State)
  1152. assert.Empty(t, got.MoodIcon)
  1153. })
  1154. }