session_test.go 46 KB

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