webapi_session_test.go 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158
  1. package state
  2. import (
  3. "context"
  4. "encoding/hex"
  5. "io"
  6. "log/slog"
  7. "testing"
  8. "time"
  9. "github.com/stretchr/testify/assert"
  10. "github.com/stretchr/testify/require"
  11. "github.com/mk6i/open-oscar-server/server/webapi/types"
  12. "github.com/mk6i/open-oscar-server/wire"
  13. )
  14. func TestWebAPISession_TempBuddies(t *testing.T) {
  15. tests := []struct {
  16. name string
  17. setupSession func() *WebAPISession
  18. operations func(*WebAPISession)
  19. expectedChecks func(*testing.T, *WebAPISession)
  20. }{
  21. {
  22. name: "Initialize_NilTempBuddies",
  23. setupSession: func() *WebAPISession {
  24. return &WebAPISession{
  25. AimSID: "test-session",
  26. ScreenName: DisplayScreenName("testuser"),
  27. EventQueue: types.NewEventQueue(100),
  28. CreatedAt: time.Now(),
  29. LastAccessed: time.Now(),
  30. ExpiresAt: time.Now().Add(time.Hour),
  31. }
  32. },
  33. operations: func(s *WebAPISession) {
  34. // Initialize TempBuddies if nil
  35. if s.TempBuddies == nil {
  36. s.TempBuddies = make(map[string]bool)
  37. }
  38. s.TempBuddies["buddy1"] = true
  39. },
  40. expectedChecks: func(t *testing.T, s *WebAPISession) {
  41. assert.NotNil(t, s.TempBuddies)
  42. assert.True(t, s.TempBuddies["buddy1"])
  43. assert.Equal(t, 1, len(s.TempBuddies))
  44. },
  45. },
  46. {
  47. name: "Add_MultipleTempBuddies",
  48. setupSession: func() *WebAPISession {
  49. return &WebAPISession{
  50. AimSID: "test-session",
  51. ScreenName: DisplayScreenName("testuser"),
  52. TempBuddies: make(map[string]bool),
  53. EventQueue: types.NewEventQueue(100),
  54. CreatedAt: time.Now(),
  55. LastAccessed: time.Now(),
  56. ExpiresAt: time.Now().Add(time.Hour),
  57. }
  58. },
  59. operations: func(s *WebAPISession) {
  60. s.TempBuddies["buddy1"] = true
  61. s.TempBuddies["buddy2"] = true
  62. s.TempBuddies["buddy3"] = true
  63. },
  64. expectedChecks: func(t *testing.T, s *WebAPISession) {
  65. assert.Equal(t, 3, len(s.TempBuddies))
  66. assert.True(t, s.TempBuddies["buddy1"])
  67. assert.True(t, s.TempBuddies["buddy2"])
  68. assert.True(t, s.TempBuddies["buddy3"])
  69. },
  70. },
  71. {
  72. name: "Add_DuplicateTempBuddy",
  73. setupSession: func() *WebAPISession {
  74. return &WebAPISession{
  75. AimSID: "test-session",
  76. ScreenName: DisplayScreenName("testuser"),
  77. TempBuddies: map[string]bool{"buddy1": true},
  78. EventQueue: types.NewEventQueue(100),
  79. CreatedAt: time.Now(),
  80. LastAccessed: time.Now(),
  81. ExpiresAt: time.Now().Add(time.Hour),
  82. }
  83. },
  84. operations: func(s *WebAPISession) {
  85. // Add the same buddy again
  86. s.TempBuddies["buddy1"] = true
  87. },
  88. expectedChecks: func(t *testing.T, s *WebAPISession) {
  89. // Should still only have one entry
  90. assert.Equal(t, 1, len(s.TempBuddies))
  91. assert.True(t, s.TempBuddies["buddy1"])
  92. },
  93. },
  94. {
  95. name: "Remove_TempBuddy",
  96. setupSession: func() *WebAPISession {
  97. return &WebAPISession{
  98. AimSID: "test-session",
  99. ScreenName: DisplayScreenName("testuser"),
  100. TempBuddies: map[string]bool{
  101. "buddy1": true,
  102. "buddy2": true,
  103. },
  104. EventQueue: types.NewEventQueue(100),
  105. CreatedAt: time.Now(),
  106. LastAccessed: time.Now(),
  107. ExpiresAt: time.Now().Add(time.Hour),
  108. }
  109. },
  110. operations: func(s *WebAPISession) {
  111. delete(s.TempBuddies, "buddy1")
  112. },
  113. expectedChecks: func(t *testing.T, s *WebAPISession) {
  114. assert.Equal(t, 1, len(s.TempBuddies))
  115. assert.False(t, s.TempBuddies["buddy1"])
  116. assert.True(t, s.TempBuddies["buddy2"])
  117. },
  118. },
  119. {
  120. name: "Check_NonExistentBuddy",
  121. setupSession: func() *WebAPISession {
  122. return &WebAPISession{
  123. AimSID: "test-session",
  124. ScreenName: DisplayScreenName("testuser"),
  125. TempBuddies: map[string]bool{"buddy1": true},
  126. EventQueue: types.NewEventQueue(100),
  127. CreatedAt: time.Now(),
  128. LastAccessed: time.Now(),
  129. ExpiresAt: time.Now().Add(time.Hour),
  130. }
  131. },
  132. operations: func(s *WebAPISession) {
  133. // No operations, just checking
  134. },
  135. expectedChecks: func(t *testing.T, s *WebAPISession) {
  136. assert.False(t, s.TempBuddies["nonexistent"])
  137. assert.True(t, s.TempBuddies["buddy1"])
  138. },
  139. },
  140. }
  141. for _, tt := range tests {
  142. t.Run(tt.name, func(t *testing.T) {
  143. // Setup
  144. session := tt.setupSession()
  145. // Perform operations
  146. tt.operations(session)
  147. // Verify
  148. tt.expectedChecks(t, session)
  149. })
  150. }
  151. }
  152. func TestWebAPISession_IsExpired(t *testing.T) {
  153. tests := []struct {
  154. name string
  155. expiresAt time.Time
  156. isExpired bool
  157. }{
  158. {
  159. name: "Not_Expired",
  160. expiresAt: time.Now().Add(time.Hour),
  161. isExpired: false,
  162. },
  163. {
  164. name: "Already_Expired",
  165. expiresAt: time.Now().Add(-time.Hour),
  166. isExpired: true,
  167. },
  168. {
  169. name: "Just_Expired",
  170. expiresAt: time.Now().Add(-time.Second),
  171. isExpired: true,
  172. },
  173. }
  174. for _, tt := range tests {
  175. t.Run(tt.name, func(t *testing.T) {
  176. session := &WebAPISession{
  177. AimSID: "test-session",
  178. ScreenName: DisplayScreenName("testuser"),
  179. ExpiresAt: tt.expiresAt,
  180. }
  181. assert.Equal(t, tt.isExpired, session.IsExpired())
  182. })
  183. }
  184. }
  185. func TestWebAPISession_WithTempBuddiesIntegration(t *testing.T) {
  186. // Test that temp buddies work correctly with a full session
  187. session := &WebAPISession{
  188. AimSID: "integration-test",
  189. ScreenName: DisplayScreenName("testuser"),
  190. EventQueue: types.NewEventQueue(100),
  191. TempBuddies: nil,
  192. CreatedAt: time.Now(),
  193. LastAccessed: time.Now(),
  194. ExpiresAt: time.Now().Add(time.Hour),
  195. FetchTimeout: 30000,
  196. }
  197. // Initialize TempBuddies
  198. session.TempBuddies = make(map[string]bool)
  199. // Simulate adding temp buddies
  200. buddies := []string{"alice", "bob", "charlie"}
  201. for _, buddy := range buddies {
  202. session.TempBuddies[buddy] = true
  203. }
  204. // Verify all buddies are present
  205. assert.Equal(t, 3, len(session.TempBuddies))
  206. for _, buddy := range buddies {
  207. assert.True(t, session.TempBuddies[buddy], "Buddy %s should be in TempBuddies", buddy)
  208. }
  209. // Test that temp buddies persist with the session
  210. assert.False(t, session.IsExpired())
  211. assert.Equal(t, "testuser", string(session.ScreenName))
  212. assert.NotNil(t, session.TempBuddies)
  213. // Simulate buddy removal
  214. delete(session.TempBuddies, "bob")
  215. assert.Equal(t, 2, len(session.TempBuddies))
  216. assert.False(t, session.TempBuddies["bob"])
  217. assert.True(t, session.TempBuddies["alice"])
  218. assert.True(t, session.TempBuddies["charlie"])
  219. }
  220. func TestWebAPISession_TempBuddiesIndependence(t *testing.T) {
  221. // Test that temp buddies are independent across sessions
  222. session1 := &WebAPISession{
  223. AimSID: "session1",
  224. ScreenName: DisplayScreenName("user1"),
  225. TempBuddies: map[string]bool{"buddy1": true},
  226. ExpiresAt: time.Now().Add(time.Hour),
  227. }
  228. session2 := &WebAPISession{
  229. AimSID: "session2",
  230. ScreenName: DisplayScreenName("user2"),
  231. TempBuddies: map[string]bool{"buddy2": true},
  232. ExpiresAt: time.Now().Add(time.Hour),
  233. }
  234. // Verify sessions have independent temp buddies
  235. assert.True(t, session1.TempBuddies["buddy1"])
  236. assert.False(t, session1.TempBuddies["buddy2"])
  237. assert.False(t, session2.TempBuddies["buddy1"])
  238. assert.True(t, session2.TempBuddies["buddy2"])
  239. // Modify one session's temp buddies
  240. session1.TempBuddies["buddy3"] = true
  241. // Verify it doesn't affect the other session
  242. assert.True(t, session1.TempBuddies["buddy3"])
  243. assert.False(t, session2.TempBuddies["buddy3"])
  244. }
  245. // TestWebAPISessionManager_ShutdownIdempotent verifies Shutdown is safe to call
  246. // more than once (e.g. from overlapping shutdown paths): the closed flag makes
  247. // the second call a no-op instead of re-draining.
  248. func TestWebAPISessionManager_ShutdownIdempotent(t *testing.T) {
  249. mgr := NewWebAPISessionManager()
  250. _ = mgr.Shutdown(context.Background())
  251. assert.NotPanics(t, func() {
  252. _ = mgr.Shutdown(context.Background())
  253. })
  254. }
  255. // TestWebAPISessionManager_CreateAfterShutdown verifies that a session cannot be
  256. // created once the manager is shut down. Otherwise the reaper is stopped and the
  257. // session would never be closed or reaped, leaking its OSCAR session.
  258. func TestWebAPISessionManager_CreateAfterShutdown(t *testing.T) {
  259. mgr := NewWebAPISessionManager()
  260. _ = mgr.Shutdown(context.Background())
  261. sess, err := mgr.CreateSession(DisplayScreenName("testuser"), "dev", []string{"presence"}, nil, "", nil)
  262. assert.Nil(t, sess)
  263. assert.ErrorIs(t, err, ErrWebAPISessionManagerClosed)
  264. }
  265. // A broadcast rate limit SNAC surfaces to the client only for the IM class: the
  266. // web client renders any rateLimit event as the conversation-window alert. Code 1
  267. // (a class-params change) is not a status transition and is dropped.
  268. func TestWebAPISession_handleRateLimitUpdate(t *testing.T) {
  269. const imClass = wire.RateLimitClassID(3)
  270. newSession := func() *WebAPISession {
  271. return &WebAPISession{
  272. IMRateClassID: imClass,
  273. EventQueue: types.NewEventQueue(10),
  274. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  275. }
  276. }
  277. rateSNAC := func(classID uint16, code uint16) wire.SNACMessage {
  278. return wire.SNACMessage{
  279. Frame: wire.SNACFrame{FoodGroup: wire.OService, SubGroup: wire.OServiceRateParamChange},
  280. Body: wire.SNAC_0x01_0x0A_OServiceRateParamsChange{Code: code, Rate: wire.RateParamsSNAC{ID: classID}},
  281. }
  282. }
  283. t.Run("IM-class transitions become rateLimit events", func(t *testing.T) {
  284. sess := newSession()
  285. sess.handleSNACMessage(rateSNAC(uint16(imClass), 3)) // limited
  286. sess.handleSNACMessage(rateSNAC(uint16(imClass), 4)) // clear
  287. events := sess.EventQueue.GetAllEvents()
  288. require.Len(t, events, 2)
  289. assert.Equal(t, "limit", events[0].Data.(types.RateLimitEvent).Classes[0].Status)
  290. assert.Equal(t, "clear", events[1].Data.(types.RateLimitEvent).Classes[0].Status)
  291. })
  292. t.Run("other classes and non-status codes are ignored", func(t *testing.T) {
  293. sess := newSession()
  294. sess.handleSNACMessage(rateSNAC(1, 3)) // class 1 limited: not the IM class
  295. sess.handleSNACMessage(rateSNAC(uint16(imClass), 1)) // IM class param change, not a status
  296. assert.Empty(t, sess.EventQueue.GetAllEvents())
  297. })
  298. t.Run("a session with no IM class disables the alert", func(t *testing.T) {
  299. sess := newSession()
  300. sess.IMRateClassID = 0
  301. sess.handleSNACMessage(rateSNAC(uint16(imClass), 3))
  302. assert.Empty(t, sess.EventQueue.GetAllEvents())
  303. })
  304. }
  305. // A rate-limit disconnect closes the account's OSCAR session; the web session's
  306. // aimsid must then stop resolving. Before this fix GetSession only checked
  307. // time-based expiry, so a client told to disconnect could keep issuing charged
  308. // requests against a dead session (and, downstream, spam clear events on every
  309. // one of them). Once the aimsid is turned away at RequireSession, neither is
  310. // possible.
  311. func TestWebAPISessionManager_GetSession_rejectsAfterRateLimitDisconnect(t *testing.T) {
  312. mgr := NewWebAPISessionManager()
  313. // A rate class that escalates to disconnect after a short back-to-back burst.
  314. var classes [5]wire.RateClass
  315. for i := range classes {
  316. classes[i] = wire.RateClass{
  317. ID: wire.RateLimitClassID(i + 1),
  318. WindowSize: 2,
  319. ClearLevel: 100,
  320. AlertLevel: 80,
  321. LimitLevel: 70,
  322. DisconnectLevel: 2,
  323. MaxLevel: 200,
  324. }
  325. }
  326. inst := NewSession().AddInstance()
  327. inst.Session().SetRateClasses(time.Now(), wire.NewRateLimitClasses(classes))
  328. sess, err := mgr.CreateSession(DisplayScreenName("advbot"), "dev", []string{"presence"}, inst, "", slog.Default())
  329. require.NoError(t, err)
  330. // Healthy session resolves.
  331. got, err := mgr.GetSession(context.Background(), sess.AimSID)
  332. require.NoError(t, err)
  333. assert.Same(t, sess, got)
  334. // Burst until EvaluateRateLimit escalates to disconnect, which closes the
  335. // account's OSCAR session.
  336. var status wire.RateLimitStatus
  337. now := time.Now()
  338. for range 10 {
  339. if status = inst.Session().EvaluateRateLimit(now, 1); status == wire.RateLimitStatusDisconnect {
  340. break
  341. }
  342. }
  343. require.Equal(t, wire.RateLimitStatusDisconnect, status)
  344. require.True(t, inst.IsClosed(), "disconnect must close the OSCAR instance")
  345. // The aimsid no longer resolves, even though ExpiresAt is far in the future.
  346. _, err = mgr.GetSession(context.Background(), sess.AimSID)
  347. assert.ErrorIs(t, err, ErrWebAPISessionExpired)
  348. assert.False(t, sess.IsExpired(), "the guard must fire on OSCAR close, not on time expiry")
  349. // The reaper frees the dead entry on its next sweep.
  350. mgr.reapExpired()
  351. assert.NotContains(t, mgr.sessions, sess.AimSID)
  352. }
  353. // TestWebAPISessionManager_ShutdownDrainsAndClosesSessions verifies that Shutdown
  354. // collects every live session and tears it down: it drains the maps and closes
  355. // each session's event queue and OSCAR instance.
  356. func TestWebAPISessionManager_ShutdownDrainsAndClosesSessions(t *testing.T) {
  357. mgr := NewWebAPISessionManager()
  358. ctx := context.Background()
  359. inst1 := NewSession().AddInstance()
  360. inst2 := NewSession().AddInstance()
  361. s1, err := mgr.CreateSession(DisplayScreenName("alice"), "dev", []string{"presence"}, inst1, "", slog.Default())
  362. assert.NoError(t, err)
  363. s2, err := mgr.CreateSession(DisplayScreenName("bob"), "dev", []string{"presence"}, inst2, "", slog.Default())
  364. assert.NoError(t, err)
  365. assert.NoError(t, mgr.Shutdown(context.Background()))
  366. // Maps drained: the collect loop ran over both sessions.
  367. assert.Empty(t, mgr.sessions)
  368. // Each session's event queue and OSCAR instance were closed: the teardown
  369. // loop ran for every collected session.
  370. for _, s := range []*WebAPISession{s1, s2} {
  371. assertQueueClosed(t, ctx, s)
  372. }
  373. for _, inst := range []*SessionInstance{inst1, inst2} {
  374. select {
  375. case <-inst.Closed():
  376. default:
  377. t.Error("OSCAR instance should be closed")
  378. }
  379. }
  380. }
  381. // TestWebAPISessionManager_ReapExpired verifies reapExpired removes and tears
  382. // down only expired sessions, leaving live ones untouched.
  383. func TestWebAPISessionManager_ReapExpired(t *testing.T) {
  384. mgr := NewWebAPISessionManager()
  385. ctx := context.Background()
  386. expiredInst := NewSession().AddInstance()
  387. liveInst := NewSession().AddInstance()
  388. expired, err := mgr.CreateSession("alice", "dev", []string{"presence"}, expiredInst, "", slog.Default())
  389. assert.NoError(t, err)
  390. live, err := mgr.CreateSession("bob", "dev", []string{"presence"}, liveInst, "", slog.Default())
  391. assert.NoError(t, err)
  392. // Force alice's session into the past; bob keeps its default future expiry.
  393. expired.ExpiresAt = time.Now().Add(-time.Minute)
  394. mgr.reapExpired()
  395. // Expired session removed; live session retained.
  396. assert.NotContains(t, mgr.sessions, expired.AimSID)
  397. assert.Contains(t, mgr.sessions, live.AimSID)
  398. // Expired session torn down: event queue and OSCAR instance closed.
  399. assertQueueClosed(t, ctx, expired)
  400. select {
  401. case <-expiredInst.Closed():
  402. default:
  403. t.Error("expired session's OSCAR instance should be closed")
  404. }
  405. // Live session left running.
  406. select {
  407. case <-liveInst.Closed():
  408. t.Error("live session's OSCAR instance should not be closed")
  409. default:
  410. }
  411. }
  412. // assertQueueClosed asserts the session's event queue is closed: a fetch returns
  413. // straight away with no events and no error, rather than parking for the timeout.
  414. func assertQueueClosed(t *testing.T, ctx context.Context, sess *WebAPISession) {
  415. t.Helper()
  416. const timeout = 5 * time.Second
  417. start := time.Now()
  418. events, err := sess.EventQueue.Fetch(ctx, 0, timeout)
  419. assert.NoError(t, err)
  420. assert.Empty(t, events)
  421. assert.Less(t, time.Since(start), timeout/2, "fetch parked instead of returning on a closed queue")
  422. }
  423. // TestWebAPISessionManager_ShutdownWithoutReaper verifies Shutdown returns when no
  424. // reaper was ever started. Shutdown must not depend on the caller cancelling the
  425. // context passed to Run.
  426. func TestWebAPISessionManager_ShutdownWithoutReaper(t *testing.T) {
  427. mgr := NewWebAPISessionManager()
  428. done := make(chan struct{})
  429. go func() {
  430. defer close(done)
  431. // This test is about Shutdown returning at all, not what it returns.
  432. _ = mgr.Shutdown(context.Background())
  433. }()
  434. select {
  435. case <-done:
  436. case <-time.After(5 * time.Second):
  437. t.Fatal("Shutdown hung waiting for a reaper that was never started")
  438. }
  439. }
  440. // TestWebAPISessionManager_ShutdownJoinsReaper verifies Shutdown stops a running
  441. // reaper on its own and does not return until that reaper has exited.
  442. func TestWebAPISessionManager_ShutdownJoinsReaper(t *testing.T) {
  443. mgr := NewWebAPISessionManager()
  444. reaperExited := make(chan struct{})
  445. go func() {
  446. defer close(reaperExited)
  447. mgr.Run(context.Background()) // context is never cancelled: Shutdown must stop it
  448. }()
  449. // Give Run a chance to register itself before shutting down.
  450. time.Sleep(50 * time.Millisecond)
  451. done := make(chan struct{})
  452. go func() {
  453. defer close(done)
  454. // This test is about Shutdown returning at all, not what it returns.
  455. _ = mgr.Shutdown(context.Background())
  456. }()
  457. select {
  458. case <-done:
  459. case <-time.After(5 * time.Second):
  460. t.Fatal("Shutdown hung instead of stopping the reaper")
  461. }
  462. // Shutdown joins the reaper, so it has already exited by the time it returns.
  463. select {
  464. case <-reaperExited:
  465. default:
  466. t.Error("Shutdown returned before the reaper exited")
  467. }
  468. }
  469. // TestWebAPISessionManager_RunAfterShutdown verifies a reaper that loses the race
  470. // with Shutdown never starts, so it cannot reap an already-drained manager.
  471. func TestWebAPISessionManager_RunAfterShutdown(t *testing.T) {
  472. mgr := NewWebAPISessionManager()
  473. assert.NoError(t, mgr.Shutdown(context.Background()))
  474. done := make(chan struct{})
  475. go func() {
  476. defer close(done)
  477. mgr.Run(context.Background())
  478. }()
  479. select {
  480. case <-done:
  481. case <-time.After(5 * time.Second):
  482. t.Fatal("Run should be a no-op on a closed manager")
  483. }
  484. }
  485. // The client deletes the alias it holds each time it merges a user map, so every
  486. // event naming a buddy has to repeat it. An incoming IM and a presence change both
  487. // carry a user map, and both would otherwise rename an aliased buddy.
  488. func TestWebAPISession_RepeatsBuddyAliasOnOSCAREvents(t *testing.T) {
  489. newSession := func() *WebAPISession {
  490. return &WebAPISession{
  491. ScreenName: DisplayScreenName("me"),
  492. Events: []string{"im", "conversation", "presence"},
  493. EventQueue: types.NewEventQueue(10),
  494. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  495. BuddyAliasLoader: func(_ context.Context) (map[string]string, error) {
  496. return map[string]string{"mikekelly": "MICHAELKELLY"}, nil
  497. },
  498. }
  499. }
  500. t.Run("incoming IM", func(t *testing.T) {
  501. sess := newSession()
  502. frags, err := wire.ICBMFragmentList("hello")
  503. require.NoError(t, err)
  504. body := wire.SNAC_0x04_0x07_ICBMChannelMsgToClient{
  505. ChannelID: wire.ICBMChannelIM,
  506. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  507. }
  508. body.Append(wire.NewTLVBE(wire.ICBMTLVAOLIMData, frags))
  509. sess.handleIncomingIM(wire.SNACMessage{Body: body})
  510. events := sess.EventQueue.GetAllEvents()
  511. require.NotEmpty(t, events)
  512. imEvent := events[0].Data.(types.IMEvent)
  513. assert.Equal(t, "mikekelly", imEvent.Source.AimID)
  514. assert.Equal(t, "Mike Kelly", imEvent.Source.DisplayID)
  515. assert.Equal(t, "MICHAELKELLY", imEvent.Source.Friendly)
  516. })
  517. t.Run("buddy arrived", func(t *testing.T) {
  518. sess := newSession()
  519. sess.handleBuddyArrived(wire.SNACMessage{Body: wire.SNAC_0x03_0x0B_BuddyArrived{
  520. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  521. }})
  522. events := sess.EventQueue.GetAllEvents()
  523. require.Len(t, events, 1)
  524. presence := events[0].Data.(types.PresenceEvent)
  525. assert.Equal(t, "mikekelly", presence.AimID)
  526. assert.Equal(t, "MICHAELKELLY", presence.Friendly)
  527. })
  528. t.Run("buddy departed", func(t *testing.T) {
  529. sess := newSession()
  530. sess.handleBuddyDeparted(wire.SNACMessage{Body: wire.SNAC_0x03_0x0C_BuddyDeparted{
  531. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  532. }})
  533. events := sess.EventQueue.GetAllEvents()
  534. require.Len(t, events, 1)
  535. presence := events[0].Data.(types.PresenceEvent)
  536. assert.Equal(t, "mikekelly", presence.AimID)
  537. assert.Equal(t, "MICHAELKELLY", presence.Friendly)
  538. })
  539. t.Run("unaliased buddy omits friendly", func(t *testing.T) {
  540. sess := newSession()
  541. sess.handleBuddyArrived(wire.SNACMessage{Body: wire.SNAC_0x03_0x0B_BuddyArrived{
  542. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Someone Else"},
  543. }})
  544. events := sess.EventQueue.GetAllEvents()
  545. require.Len(t, events, 1)
  546. assert.Empty(t, events[0].Data.(types.PresenceEvent).Friendly)
  547. })
  548. }
  549. // Aliases all come from one feedbag query, so a signon that brings a whole buddy
  550. // list online must not re-query the feedbag per buddy.
  551. func TestWebAPISession_CachesBuddyAliases(t *testing.T) {
  552. var loads int
  553. sess := &WebAPISession{
  554. ScreenName: DisplayScreenName("me"),
  555. Events: []string{"presence"},
  556. EventQueue: types.NewEventQueue(10),
  557. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  558. BuddyAliasLoader: func(_ context.Context) (map[string]string, error) {
  559. loads++
  560. return map[string]string{"mikekelly": "MICHAELKELLY"}, nil
  561. },
  562. }
  563. for range 5 {
  564. sess.handleBuddyArrived(wire.SNACMessage{Body: wire.SNAC_0x03_0x0B_BuddyArrived{
  565. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  566. }})
  567. }
  568. events := sess.EventQueue.GetAllEvents()
  569. require.Len(t, events, 5)
  570. for _, event := range events {
  571. assert.Equal(t, "MICHAELKELLY", event.Data.(types.PresenceEvent).Friendly)
  572. }
  573. assert.Equal(t, 1, loads, "aliases should be loaded once, not once per event")
  574. }
  575. // A feedbag change from another of the owner's clients arrives as a SNAC, which is
  576. // the session's only signal that its cached aliases are stale.
  577. func TestWebAPISession_FeedbagSNACInvalidatesAliasCache(t *testing.T) {
  578. alias := "MICHAELKELLY"
  579. sess := &WebAPISession{
  580. ScreenName: DisplayScreenName("me"),
  581. Events: []string{"presence"},
  582. EventQueue: types.NewEventQueue(10),
  583. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  584. BuddyAliasLoader: func(_ context.Context) (map[string]string, error) {
  585. return map[string]string{"mikekelly": alias}, nil
  586. },
  587. }
  588. arrive := func() types.PresenceEvent {
  589. sess.handleBuddyArrived(wire.SNACMessage{Body: wire.SNAC_0x03_0x0B_BuddyArrived{
  590. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  591. }})
  592. events := sess.EventQueue.GetAllEvents()
  593. require.NotEmpty(t, events)
  594. return events[len(events)-1].Data.(types.PresenceEvent)
  595. }
  596. assert.Equal(t, "MICHAELKELLY", arrive().Friendly)
  597. // The buddy is renamed elsewhere: the feedbag SNAC must drop the cached map.
  598. alias = "MIKE"
  599. sess.handleFeedbagMessage(wire.SNACMessage{
  600. Frame: wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagUpdateItem},
  601. Body: wire.SNAC_0x13_0x09_FeedbagUpdateItem{},
  602. })
  603. assert.Equal(t, "MIKE", arrive().Friendly)
  604. }
  605. // Permit/deny changes from another of the owner's clients arrive as an insert,
  606. // an update, or a delete, and all three have to refresh the client's privacy
  607. // state.
  608. func TestWebAPISession_FeedbagSNACRefreshesPermitDeny(t *testing.T) {
  609. denyItem := wire.FeedbagItem{ClassID: wire.FeedbagClassIDDeny, Name: "blockeduser"}
  610. buddyItem := wire.FeedbagItem{ClassID: wire.FeedbagClassIdBuddy, Name: "friend"}
  611. tests := []struct {
  612. name string
  613. subGroup uint16
  614. body any
  615. wantEvent bool
  616. }{
  617. {
  618. name: "insert relays an update body",
  619. subGroup: wire.FeedbagInsertItem,
  620. body: wire.SNAC_0x13_0x09_FeedbagUpdateItem{Items: []wire.FeedbagItem{denyItem}},
  621. wantEvent: true,
  622. },
  623. {
  624. name: "update",
  625. subGroup: wire.FeedbagUpdateItem,
  626. body: wire.SNAC_0x13_0x09_FeedbagUpdateItem{Items: []wire.FeedbagItem{denyItem}},
  627. wantEvent: true,
  628. },
  629. {
  630. name: "delete",
  631. subGroup: wire.FeedbagDeleteItem,
  632. body: wire.SNAC_0x13_0x0A_FeedbagDeleteItem{Items: []wire.FeedbagItem{denyItem}},
  633. wantEvent: true,
  634. },
  635. {
  636. name: "buddy item only",
  637. subGroup: wire.FeedbagInsertItem,
  638. body: wire.SNAC_0x13_0x09_FeedbagUpdateItem{Items: []wire.FeedbagItem{buddyItem}},
  639. wantEvent: false,
  640. },
  641. }
  642. for _, tt := range tests {
  643. t.Run(tt.name, func(t *testing.T) {
  644. sess := &WebAPISession{
  645. ScreenName: DisplayScreenName("me"),
  646. EventQueue: types.NewEventQueue(10),
  647. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  648. PermitDenyRefresher: func(_ context.Context) (interface{}, error) {
  649. return map[string]any{"pdMode": "denySome"}, nil
  650. },
  651. }
  652. sess.handleFeedbagMessage(wire.SNACMessage{
  653. Frame: wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: tt.subGroup},
  654. Body: tt.body,
  655. })
  656. var got int
  657. for _, event := range sess.EventQueue.GetAllEvents() {
  658. if event.Type == types.EventTypePermitDeny {
  659. got++
  660. }
  661. }
  662. if tt.wantEvent {
  663. assert.Equal(t, 1, got)
  664. } else {
  665. assert.Zero(t, got)
  666. }
  667. })
  668. }
  669. }
  670. // A session sees no SNAC for feedbag writes it makes itself, so the handlers that
  671. // perform those writes invalidate the cache directly.
  672. func TestWebAPISession_InvalidateAliases(t *testing.T) {
  673. alias := "MICHAELKELLY"
  674. sess := &WebAPISession{
  675. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  676. BuddyAliasLoader: func(_ context.Context) (map[string]string, error) {
  677. return map[string]string{"mikekelly": alias}, nil
  678. },
  679. }
  680. assert.Equal(t, "MICHAELKELLY", sess.Aliases(context.Background())["mikekelly"])
  681. alias = "MIKE"
  682. assert.Equal(t, "MICHAELKELLY", sess.Aliases(context.Background())["mikekelly"], "cached until invalidated")
  683. sess.InvalidateAliases()
  684. assert.Equal(t, "MIKE", sess.Aliases(context.Background())["mikekelly"])
  685. }
  686. // A failed load must not be cached as an empty map: aliases would stay missing for
  687. // the life of the session.
  688. func TestWebAPISession_AliasLoadErrorIsNotCached(t *testing.T) {
  689. var loads int
  690. sess := &WebAPISession{
  691. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  692. BuddyAliasLoader: func(_ context.Context) (map[string]string, error) {
  693. loads++
  694. if loads == 1 {
  695. return nil, io.EOF
  696. }
  697. return map[string]string{"mikekelly": "MICHAELKELLY"}, nil
  698. },
  699. }
  700. assert.Empty(t, sess.Aliases(context.Background()))
  701. assert.Equal(t, "MICHAELKELLY", sess.Aliases(context.Background())["mikekelly"])
  702. }
  703. func TestWebAPISession_HandleIncomingIM_NormalizesAimID(t *testing.T) {
  704. sess := &WebAPISession{
  705. ScreenName: DisplayScreenName("me"),
  706. Events: []string{"im", "conversation"},
  707. EventQueue: types.NewEventQueue(10),
  708. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  709. }
  710. frags, err := wire.ICBMFragmentList("hello")
  711. assert.NoError(t, err)
  712. body := wire.SNAC_0x04_0x07_ICBMChannelMsgToClient{
  713. ChannelID: wire.ICBMChannelIM,
  714. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  715. }
  716. body.Append(wire.NewTLVBE(wire.ICBMTLVAOLIMData, frags))
  717. sess.handleIncomingIM(wire.SNACMessage{Body: body})
  718. events := sess.EventQueue.GetAllEvents()
  719. require.Len(t, events, 2)
  720. imEvent := events[0].Data.(types.IMEvent)
  721. assert.Equal(t, "mikekelly", imEvent.Source.AimID)
  722. assert.Equal(t, "Mike Kelly", imEvent.Source.DisplayID)
  723. convData := events[1].Data.(*types.ConversationData)
  724. require.Len(t, convData.Conversations, 1)
  725. entry := convData.Conversations[0]
  726. assert.Equal(t, "mikekelly", entry.AimID)
  727. assert.Equal(t, "Mike Kelly", entry.DisplayID)
  728. require.NotNil(t, entry.LastIM)
  729. assert.Equal(t, "mikekelly", entry.LastIM.Sender)
  730. // The IM log is keyed by aimId, so the conversation the client opens from
  731. // this event finds its own history.
  732. msgs := sess.GetStoredIMs(StoredIMQuery{PartnerAimID: "mikekelly", NToGet: 10})
  733. require.Len(t, msgs, 1)
  734. assert.Equal(t, "hello", msgs[0].Message)
  735. }
  736. func TestWebAPISession_HandleTypingNotification_NormalizesAimID(t *testing.T) {
  737. sess := &WebAPISession{
  738. Events: []string{"typing"},
  739. EventQueue: types.NewEventQueue(10),
  740. }
  741. sess.handleTypingNotification(wire.SNACMessage{
  742. Body: wire.SNAC_0x04_0x14_ICBMClientEvent{
  743. ScreenName: "Mike Kelly",
  744. Event: 0x0002,
  745. },
  746. })
  747. events := sess.EventQueue.GetAllEvents()
  748. require.Len(t, events, 1)
  749. typing := events[0].Data.(types.TypingEvent)
  750. assert.Equal(t, "mikekelly", typing.AimID)
  751. assert.Equal(t, "typing", typing.TypingStatus)
  752. }
  753. func TestWebAPISession_HandleBuddyArrivedDeparted_NormalizesAimID(t *testing.T) {
  754. sess := &WebAPISession{
  755. Events: []string{"presence"},
  756. EventQueue: types.NewEventQueue(10),
  757. }
  758. sess.handleBuddyArrived(wire.SNACMessage{
  759. Body: wire.SNAC_0x03_0x0B_BuddyArrived{
  760. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  761. },
  762. })
  763. sess.handleBuddyDeparted(wire.SNACMessage{
  764. Body: wire.SNAC_0x03_0x0C_BuddyDeparted{
  765. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  766. },
  767. })
  768. events := sess.EventQueue.GetAllEvents()
  769. require.Len(t, events, 2)
  770. arrived := events[0].Data.(types.PresenceEvent)
  771. assert.Equal(t, "mikekelly", arrived.AimID)
  772. assert.Equal(t, "online", arrived.State)
  773. departed := events[1].Data.(types.PresenceEvent)
  774. assert.Equal(t, "mikekelly", departed.AimID)
  775. assert.Equal(t, "offline", departed.State)
  776. }
  777. // A BuddyArrived carries the buddy's current icon as TLV 0x1D, so an icon change
  778. // rides along on the presence broadcast and must reach the presence event. The
  779. // stub BuddyIconURL stands in for the handlers-side URL formatter, which state
  780. // cannot import.
  781. func TestWebAPISession_PublishesBuddyIconOnPresence(t *testing.T) {
  782. newSession := func() *WebAPISession {
  783. return &WebAPISession{
  784. ScreenName: DisplayScreenName("me"),
  785. Events: []string{"presence"},
  786. EventQueue: types.NewEventQueue(10),
  787. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  788. BuddyIconURL: func(sn IdentScreenName, hash []byte) string {
  789. if len(hash) == 0 {
  790. return "placeholder:" + sn.String()
  791. }
  792. return "icon:" + hex.EncodeToString(hash)
  793. },
  794. }
  795. }
  796. arrived := func(sess *WebAPISession, screenName string, hash []byte) {
  797. info := wire.TLVUserInfo{ScreenName: screenName}
  798. if hash != nil {
  799. info.Append(wire.NewTLVBE(wire.OServiceUserInfoBARTInfo, wire.BARTID{
  800. Type: wire.BARTTypesBuddyIcon,
  801. BARTInfo: wire.BARTInfo{Hash: hash},
  802. }))
  803. }
  804. sess.handleBuddyArrived(wire.SNACMessage{Body: wire.SNAC_0x03_0x0B_BuddyArrived{TLVUserInfo: info}})
  805. }
  806. lastPresence := func(sess *WebAPISession) types.PresenceEvent {
  807. events := sess.EventQueue.GetAllEvents()
  808. require.Len(t, events, 1)
  809. return events[0].Data.(types.PresenceEvent)
  810. }
  811. t.Run("icon hash yields the content-addressed URL", func(t *testing.T) {
  812. sess := newSession()
  813. arrived(sess, "Mike Kelly", []byte{0xde, 0xad, 0xbe, 0xef})
  814. assert.Equal(t, "icon:deadbeef", lastPresence(sess).BuddyIcon)
  815. })
  816. t.Run("no icon TLV yields the placeholder URL", func(t *testing.T) {
  817. sess := newSession()
  818. arrived(sess, "Mike Kelly", nil)
  819. assert.Equal(t, "placeholder:mikekelly", lastPresence(sess).BuddyIcon)
  820. })
  821. t.Run("cleared icon yields a URL naming the sentinel hash", func(t *testing.T) {
  822. sess := newSession()
  823. arrived(sess, "Mike Kelly", wire.GetClearIconHash())
  824. assert.Equal(t, "icon:"+hex.EncodeToString(wire.GetClearIconHash()), lastPresence(sess).BuddyIcon)
  825. })
  826. t.Run("departed omits the icon so the client preserves it", func(t *testing.T) {
  827. sess := newSession()
  828. sess.handleBuddyDeparted(wire.SNACMessage{Body: wire.SNAC_0x03_0x0C_BuddyDeparted{
  829. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  830. }})
  831. assert.Empty(t, lastPresence(sess).BuddyIcon)
  832. })
  833. t.Run("no callback wired omits the icon", func(t *testing.T) {
  834. sess := newSession()
  835. sess.BuddyIconURL = nil
  836. arrived(sess, "Mike Kelly", []byte{0x01})
  837. assert.Empty(t, lastPresence(sess).BuddyIcon)
  838. })
  839. }
  840. // A user's own icon change is relayed to their session as OServiceUserInfoUpdate,
  841. // which the pump turns into a myInfo event so the identity badge re-renders.
  842. func TestWebAPISession_PushesMyInfoOnUserInfoUpdate(t *testing.T) {
  843. newSession := func(events ...string) (*WebAPISession, *int) {
  844. var refreshes int
  845. return &WebAPISession{
  846. ScreenName: DisplayScreenName("me"),
  847. Events: events,
  848. EventQueue: types.NewEventQueue(10),
  849. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  850. MyInfoRefresher: func(_ context.Context) (interface{}, error) {
  851. refreshes++
  852. return map[string]interface{}{"aimId": "me", "buddyIcon": "icon:new"}, nil
  853. },
  854. }, &refreshes
  855. }
  856. userInfoUpdate := wire.SNACMessage{Frame: wire.SNACFrame{
  857. FoodGroup: wire.OService,
  858. SubGroup: wire.OServiceUserInfoUpdate,
  859. }}
  860. t.Run("subscribed session gets one myInfo event", func(t *testing.T) {
  861. sess, refreshes := newSession("myInfo")
  862. sess.handleSNACMessage(userInfoUpdate)
  863. events := sess.EventQueue.GetAllEvents()
  864. require.Len(t, events, 1)
  865. assert.Equal(t, "myInfo", string(events[0].Type))
  866. assert.Equal(t, "icon:new", events[0].Data.(map[string]interface{})["buddyIcon"])
  867. assert.Equal(t, 1, *refreshes)
  868. })
  869. t.Run("a presence subscription also delivers myInfo", func(t *testing.T) {
  870. sess, _ := newSession("presence")
  871. sess.handleSNACMessage(userInfoUpdate)
  872. assert.Len(t, sess.EventQueue.GetAllEvents(), 1)
  873. })
  874. t.Run("unsubscribed session gets nothing and does not refresh", func(t *testing.T) {
  875. sess, refreshes := newSession("im")
  876. sess.handleSNACMessage(userInfoUpdate)
  877. assert.Empty(t, sess.EventQueue.GetAllEvents())
  878. assert.Equal(t, 0, *refreshes)
  879. })
  880. t.Run("other OService subgroups are ignored", func(t *testing.T) {
  881. sess, refreshes := newSession("myInfo")
  882. sess.handleSNACMessage(wire.SNACMessage{Frame: wire.SNACFrame{
  883. FoodGroup: wire.OService,
  884. SubGroup: wire.OServiceRateParamsQuery,
  885. }})
  886. assert.Empty(t, sess.EventQueue.GetAllEvents())
  887. assert.Equal(t, 0, *refreshes)
  888. })
  889. }
  890. // TestWebAPISessionManager_ShutdownBoundedByContext verifies that Shutdown
  891. // honors its context instead of blocking indefinitely. A listener goroutine that
  892. // ignores cancellation must not be able to hold the whole server open: main
  893. // budgets a few seconds for every server's shutdown combined, so an unbounded
  894. // wait here means the process never exits.
  895. func TestWebAPISessionManager_ShutdownBoundedByContext(t *testing.T) {
  896. mgr := NewWebAPISessionManager()
  897. inst := NewSession().AddInstance()
  898. sess, err := mgr.CreateSession("alice", "dev", []string{"presence"}, inst, "", slog.Default())
  899. assert.NoError(t, err)
  900. // Stand in for a listener wedged somewhere that never observes cancellation.
  901. release := make(chan struct{})
  902. defer close(release)
  903. sess.listeners.Add(1)
  904. go func() {
  905. defer sess.listeners.Done()
  906. <-release
  907. }()
  908. ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
  909. defer cancel()
  910. start := time.Now()
  911. err = mgr.Shutdown(ctx)
  912. elapsed := time.Since(start)
  913. assert.ErrorIs(t, err, context.DeadlineExceeded)
  914. assert.Less(t, elapsed, 2*time.Second, "Shutdown must give up at its deadline, not wait on the stuck listener")
  915. }
  916. // TestWebAPISession_CloseCancelsSessionContext verifies that Close cancels the
  917. // context handed to the refresher callbacks. The listener runs feedbag queries
  918. // through it, and without cancellation Close's wait lasts as long as the query.
  919. func TestWebAPISession_CloseCancelsSessionContext(t *testing.T) {
  920. mgr := NewWebAPISessionManager()
  921. inst := NewSession().AddInstance()
  922. sess, err := mgr.CreateSession("alice", "dev", []string{"presence"}, inst, "", slog.Default())
  923. assert.NoError(t, err)
  924. assert.NoError(t, sess.ctx.Err(), "session context should be live before Close")
  925. sess.Close()
  926. assert.ErrorIs(t, sess.ctx.Err(), context.Canceled)
  927. }
  928. // A message replayed out of the offline store arrives as an ordinary
  929. // ICBMChannelMsgToClient stamped with a send time. The client models that as its
  930. // own offlineIM event, keyed by a bare aimId and timestamped when the sender sent
  931. // it rather than when it was delivered.
  932. func TestWebAPISession_OfflineIM(t *testing.T) {
  933. sentAt := time.Now().Add(-2 * time.Hour).Unix()
  934. newSession := func(events ...string) *WebAPISession {
  935. return &WebAPISession{
  936. ScreenName: DisplayScreenName("me"),
  937. Events: events,
  938. EventQueue: types.NewEventQueue(10),
  939. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  940. }
  941. }
  942. storedMsg := func(t *testing.T, withSendTime bool) wire.SNACMessage {
  943. t.Helper()
  944. frags, err := wire.ICBMFragmentList("sent while you were out")
  945. require.NoError(t, err)
  946. body := wire.SNAC_0x04_0x07_ICBMChannelMsgToClient{
  947. ChannelID: wire.ICBMChannelIM,
  948. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  949. }
  950. body.Append(wire.NewTLVBE(wire.ICBMTLVAOLIMData, frags))
  951. if withSendTime {
  952. body.Append(wire.NewTLVBE(wire.ICBMTLVSendTime, uint32(sentAt)))
  953. }
  954. return wire.SNACMessage{Body: body}
  955. }
  956. t.Run("send time yields an offlineIM event", func(t *testing.T) {
  957. sess := newSession("im", "offlineIM")
  958. sess.handleIncomingIM(storedMsg(t, true))
  959. events := sess.EventQueue.GetAllEvents()
  960. require.Len(t, events, 1)
  961. assert.Equal(t, types.EventTypeOfflineIM, events[0].Type)
  962. offline := events[0].Data.(types.OfflineIMEvent)
  963. assert.Equal(t, "mikekelly", offline.AimID)
  964. assert.Equal(t, "sent while you were out", offline.Message)
  965. assert.NotEmpty(t, offline.MsgID)
  966. assert.Equal(t, float64(sentAt), offline.Timestamp)
  967. })
  968. t.Run("no send time yields an im event", func(t *testing.T) {
  969. sess := newSession("im", "offlineIM")
  970. sess.handleIncomingIM(storedMsg(t, false))
  971. events := sess.EventQueue.GetAllEvents()
  972. require.Len(t, events, 1)
  973. assert.Equal(t, types.EventTypeIM, events[0].Type)
  974. })
  975. t.Run("offlineIM subscriber gets a conversation update", func(t *testing.T) {
  976. sess := newSession("offlineIM", "conversation")
  977. sess.handleIncomingIM(storedMsg(t, true))
  978. events := sess.EventQueue.GetAllEvents()
  979. require.Len(t, events, 2)
  980. assert.Equal(t, types.EventTypeOfflineIM, events[0].Type)
  981. assert.Equal(t, types.EventTypeConversation, events[1].Type)
  982. })
  983. // The history the client pulls with fetchStoredIMs has to order the message by
  984. // when it was sent, not when the session that drained the store started.
  985. t.Run("logs the message under its send time", func(t *testing.T) {
  986. sess := newSession("offlineIM")
  987. sess.handleIncomingIM(storedMsg(t, true))
  988. stored := sess.GetStoredIMs(StoredIMQuery{PartnerAimID: "mikekelly", NToGet: 10})
  989. require.Len(t, stored, 1)
  990. assert.Equal(t, float64(sentAt), stored[0].Date)
  991. })
  992. // Only a live IM is filtered on subscription here. Retrieval answers the
  993. // instance that asked and StartSession asks only for an offlineIM subscriber,
  994. // so a stamped message reaching a session that did not subscribe is not a state
  995. // this handler can be put in.
  996. t.Run("no subscription drops a live message", func(t *testing.T) {
  997. sess := newSession("presence")
  998. sess.handleIncomingIM(storedMsg(t, false))
  999. assert.Empty(t, sess.EventQueue.GetAllEvents())
  1000. })
  1001. }