webapi_session_test.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  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. // TestWebAPISessionManager_ShutdownDrainsAndClosesSessions verifies that Shutdown
  266. // collects every live session and tears it down: it drains the maps and closes
  267. // each session's event queue and OSCAR instance.
  268. func TestWebAPISessionManager_ShutdownDrainsAndClosesSessions(t *testing.T) {
  269. mgr := NewWebAPISessionManager()
  270. ctx := context.Background()
  271. inst1 := NewSession().AddInstance()
  272. inst2 := NewSession().AddInstance()
  273. s1, err := mgr.CreateSession(DisplayScreenName("alice"), "dev", []string{"presence"}, inst1, "", slog.Default())
  274. assert.NoError(t, err)
  275. s2, err := mgr.CreateSession(DisplayScreenName("bob"), "dev", []string{"presence"}, inst2, "", slog.Default())
  276. assert.NoError(t, err)
  277. mgr.Shutdown(context.Background())
  278. // Maps drained: the collect loop ran over both sessions.
  279. assert.Empty(t, mgr.sessions)
  280. // Each session's event queue and OSCAR instance were closed: the teardown
  281. // loop ran for every collected session.
  282. for _, s := range []*WebAPISession{s1, s2} {
  283. assertQueueClosed(t, ctx, s)
  284. }
  285. for _, inst := range []*SessionInstance{inst1, inst2} {
  286. select {
  287. case <-inst.Closed():
  288. default:
  289. t.Error("OSCAR instance should be closed")
  290. }
  291. }
  292. }
  293. // TestWebAPISessionManager_ReapExpired verifies reapExpired removes and tears
  294. // down only expired sessions, leaving live ones untouched.
  295. func TestWebAPISessionManager_ReapExpired(t *testing.T) {
  296. mgr := NewWebAPISessionManager()
  297. ctx := context.Background()
  298. expiredInst := NewSession().AddInstance()
  299. liveInst := NewSession().AddInstance()
  300. expired, err := mgr.CreateSession("alice", "dev", []string{"presence"}, expiredInst, "", slog.Default())
  301. assert.NoError(t, err)
  302. live, err := mgr.CreateSession("bob", "dev", []string{"presence"}, liveInst, "", slog.Default())
  303. assert.NoError(t, err)
  304. // Force alice's session into the past; bob keeps its default future expiry.
  305. expired.ExpiresAt = time.Now().Add(-time.Minute)
  306. mgr.reapExpired()
  307. // Expired session removed; live session retained.
  308. assert.NotContains(t, mgr.sessions, expired.AimSID)
  309. assert.Contains(t, mgr.sessions, live.AimSID)
  310. // Expired session torn down: event queue and OSCAR instance closed.
  311. assertQueueClosed(t, ctx, expired)
  312. select {
  313. case <-expiredInst.Closed():
  314. default:
  315. t.Error("expired session's OSCAR instance should be closed")
  316. }
  317. // Live session left running.
  318. select {
  319. case <-liveInst.Closed():
  320. t.Error("live session's OSCAR instance should not be closed")
  321. default:
  322. }
  323. }
  324. // assertQueueClosed asserts the session's event queue is closed: a fetch returns
  325. // straight away with no events and no error, rather than parking for the timeout.
  326. func assertQueueClosed(t *testing.T, ctx context.Context, sess *WebAPISession) {
  327. t.Helper()
  328. const timeout = 5 * time.Second
  329. start := time.Now()
  330. events, err := sess.EventQueue.Fetch(ctx, 0, timeout)
  331. assert.NoError(t, err)
  332. assert.Empty(t, events)
  333. assert.Less(t, time.Since(start), timeout/2, "fetch parked instead of returning on a closed queue")
  334. }
  335. // TestWebAPISessionManager_ShutdownWithoutReaper verifies Shutdown returns when no
  336. // reaper was ever started. Shutdown must not depend on the caller cancelling the
  337. // context passed to Run.
  338. func TestWebAPISessionManager_ShutdownWithoutReaper(t *testing.T) {
  339. mgr := NewWebAPISessionManager()
  340. done := make(chan struct{})
  341. go func() {
  342. defer close(done)
  343. mgr.Shutdown(context.Background())
  344. }()
  345. select {
  346. case <-done:
  347. case <-time.After(5 * time.Second):
  348. t.Fatal("Shutdown hung waiting for a reaper that was never started")
  349. }
  350. }
  351. // TestWebAPISessionManager_ShutdownJoinsReaper verifies Shutdown stops a running
  352. // reaper on its own and does not return until that reaper has exited.
  353. func TestWebAPISessionManager_ShutdownJoinsReaper(t *testing.T) {
  354. mgr := NewWebAPISessionManager()
  355. reaperExited := make(chan struct{})
  356. go func() {
  357. defer close(reaperExited)
  358. mgr.Run(context.Background()) // context is never cancelled: Shutdown must stop it
  359. }()
  360. // Give Run a chance to register itself before shutting down.
  361. time.Sleep(50 * time.Millisecond)
  362. done := make(chan struct{})
  363. go func() {
  364. defer close(done)
  365. mgr.Shutdown(context.Background())
  366. }()
  367. select {
  368. case <-done:
  369. case <-time.After(5 * time.Second):
  370. t.Fatal("Shutdown hung instead of stopping the reaper")
  371. }
  372. // Shutdown joins the reaper, so it has already exited by the time it returns.
  373. select {
  374. case <-reaperExited:
  375. default:
  376. t.Error("Shutdown returned before the reaper exited")
  377. }
  378. }
  379. // TestWebAPISessionManager_RunAfterShutdown verifies a reaper that loses the race
  380. // with Shutdown never starts, so it cannot reap an already-drained manager.
  381. func TestWebAPISessionManager_RunAfterShutdown(t *testing.T) {
  382. mgr := NewWebAPISessionManager()
  383. mgr.Shutdown(context.Background())
  384. done := make(chan struct{})
  385. go func() {
  386. defer close(done)
  387. mgr.Run(context.Background())
  388. }()
  389. select {
  390. case <-done:
  391. case <-time.After(5 * time.Second):
  392. t.Fatal("Run should be a no-op on a closed manager")
  393. }
  394. }
  395. // The client deletes the alias it holds each time it merges a user map, so every
  396. // event naming a buddy has to repeat it. An incoming IM and a presence change both
  397. // carry a user map, and both would otherwise rename an aliased buddy.
  398. func TestWebAPISession_RepeatsBuddyAliasOnOSCAREvents(t *testing.T) {
  399. newSession := func() *WebAPISession {
  400. return &WebAPISession{
  401. ScreenName: DisplayScreenName("me"),
  402. Events: []string{"im", "conversation", "presence"},
  403. EventQueue: types.NewEventQueue(10),
  404. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  405. BuddyAliasLoader: func(_ context.Context) (map[string]string, error) {
  406. return map[string]string{"mikekelly": "MICHAELKELLY"}, nil
  407. },
  408. }
  409. }
  410. t.Run("incoming IM", func(t *testing.T) {
  411. sess := newSession()
  412. frags, err := wire.ICBMFragmentList("hello")
  413. require.NoError(t, err)
  414. body := wire.SNAC_0x04_0x07_ICBMChannelMsgToClient{
  415. ChannelID: wire.ICBMChannelIM,
  416. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  417. }
  418. body.Append(wire.NewTLVBE(wire.ICBMTLVAOLIMData, frags))
  419. sess.handleIncomingIM(wire.SNACMessage{Body: body})
  420. events := sess.EventQueue.GetAllEvents()
  421. require.NotEmpty(t, events)
  422. imEvent := events[0].Data.(types.IMEvent)
  423. assert.Equal(t, "mikekelly", imEvent.Source.AimID)
  424. assert.Equal(t, "Mike Kelly", imEvent.Source.DisplayID)
  425. assert.Equal(t, "MICHAELKELLY", imEvent.Source.Friendly)
  426. })
  427. t.Run("buddy arrived", func(t *testing.T) {
  428. sess := newSession()
  429. sess.handleBuddyArrived(wire.SNACMessage{Body: wire.SNAC_0x03_0x0B_BuddyArrived{
  430. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  431. }})
  432. events := sess.EventQueue.GetAllEvents()
  433. require.Len(t, events, 1)
  434. presence := events[0].Data.(types.PresenceEvent)
  435. assert.Equal(t, "mikekelly", presence.AimID)
  436. assert.Equal(t, "MICHAELKELLY", presence.Friendly)
  437. })
  438. t.Run("buddy departed", func(t *testing.T) {
  439. sess := newSession()
  440. sess.handleBuddyDeparted(wire.SNACMessage{Body: wire.SNAC_0x03_0x0C_BuddyDeparted{
  441. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  442. }})
  443. events := sess.EventQueue.GetAllEvents()
  444. require.Len(t, events, 1)
  445. presence := events[0].Data.(types.PresenceEvent)
  446. assert.Equal(t, "mikekelly", presence.AimID)
  447. assert.Equal(t, "MICHAELKELLY", presence.Friendly)
  448. })
  449. t.Run("unaliased buddy omits friendly", func(t *testing.T) {
  450. sess := newSession()
  451. sess.handleBuddyArrived(wire.SNACMessage{Body: wire.SNAC_0x03_0x0B_BuddyArrived{
  452. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Someone Else"},
  453. }})
  454. events := sess.EventQueue.GetAllEvents()
  455. require.Len(t, events, 1)
  456. assert.Empty(t, events[0].Data.(types.PresenceEvent).Friendly)
  457. })
  458. }
  459. // Aliases all come from one feedbag query, so a signon that brings a whole buddy
  460. // list online must not re-query the feedbag per buddy.
  461. func TestWebAPISession_CachesBuddyAliases(t *testing.T) {
  462. var loads int
  463. sess := &WebAPISession{
  464. ScreenName: DisplayScreenName("me"),
  465. Events: []string{"presence"},
  466. EventQueue: types.NewEventQueue(10),
  467. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  468. BuddyAliasLoader: func(_ context.Context) (map[string]string, error) {
  469. loads++
  470. return map[string]string{"mikekelly": "MICHAELKELLY"}, nil
  471. },
  472. }
  473. for range 5 {
  474. sess.handleBuddyArrived(wire.SNACMessage{Body: wire.SNAC_0x03_0x0B_BuddyArrived{
  475. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  476. }})
  477. }
  478. events := sess.EventQueue.GetAllEvents()
  479. require.Len(t, events, 5)
  480. for _, event := range events {
  481. assert.Equal(t, "MICHAELKELLY", event.Data.(types.PresenceEvent).Friendly)
  482. }
  483. assert.Equal(t, 1, loads, "aliases should be loaded once, not once per event")
  484. }
  485. // A feedbag change from another of the owner's clients arrives as a SNAC, which is
  486. // the session's only signal that its cached aliases are stale.
  487. func TestWebAPISession_FeedbagSNACInvalidatesAliasCache(t *testing.T) {
  488. alias := "MICHAELKELLY"
  489. sess := &WebAPISession{
  490. ScreenName: DisplayScreenName("me"),
  491. Events: []string{"presence"},
  492. EventQueue: types.NewEventQueue(10),
  493. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  494. BuddyAliasLoader: func(_ context.Context) (map[string]string, error) {
  495. return map[string]string{"mikekelly": alias}, nil
  496. },
  497. }
  498. arrive := func() types.PresenceEvent {
  499. sess.handleBuddyArrived(wire.SNACMessage{Body: wire.SNAC_0x03_0x0B_BuddyArrived{
  500. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  501. }})
  502. events := sess.EventQueue.GetAllEvents()
  503. require.NotEmpty(t, events)
  504. return events[len(events)-1].Data.(types.PresenceEvent)
  505. }
  506. assert.Equal(t, "MICHAELKELLY", arrive().Friendly)
  507. // The buddy is renamed elsewhere: the feedbag SNAC must drop the cached map.
  508. alias = "MIKE"
  509. sess.handleFeedbagMessage(wire.SNACMessage{
  510. Frame: wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagUpdateItem},
  511. Body: wire.SNAC_0x13_0x09_FeedbagUpdateItem{},
  512. })
  513. assert.Equal(t, "MIKE", arrive().Friendly)
  514. }
  515. // A session sees no SNAC for feedbag writes it makes itself, so the handlers that
  516. // perform those writes invalidate the cache directly.
  517. func TestWebAPISession_InvalidateAliases(t *testing.T) {
  518. alias := "MICHAELKELLY"
  519. sess := &WebAPISession{
  520. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  521. BuddyAliasLoader: func(_ context.Context) (map[string]string, error) {
  522. return map[string]string{"mikekelly": alias}, nil
  523. },
  524. }
  525. assert.Equal(t, "MICHAELKELLY", sess.Aliases(context.Background())["mikekelly"])
  526. alias = "MIKE"
  527. assert.Equal(t, "MICHAELKELLY", sess.Aliases(context.Background())["mikekelly"], "cached until invalidated")
  528. sess.InvalidateAliases()
  529. assert.Equal(t, "MIKE", sess.Aliases(context.Background())["mikekelly"])
  530. }
  531. // A failed load must not be cached as an empty map: aliases would stay missing for
  532. // the life of the session.
  533. func TestWebAPISession_AliasLoadErrorIsNotCached(t *testing.T) {
  534. var loads int
  535. sess := &WebAPISession{
  536. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  537. BuddyAliasLoader: func(_ context.Context) (map[string]string, error) {
  538. loads++
  539. if loads == 1 {
  540. return nil, io.EOF
  541. }
  542. return map[string]string{"mikekelly": "MICHAELKELLY"}, nil
  543. },
  544. }
  545. assert.Empty(t, sess.Aliases(context.Background()))
  546. assert.Equal(t, "MICHAELKELLY", sess.Aliases(context.Background())["mikekelly"])
  547. }
  548. func TestWebAPISession_HandleIncomingIM_NormalizesAimID(t *testing.T) {
  549. sess := &WebAPISession{
  550. ScreenName: DisplayScreenName("me"),
  551. Events: []string{"im", "conversation"},
  552. EventQueue: types.NewEventQueue(10),
  553. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  554. }
  555. frags, err := wire.ICBMFragmentList("hello")
  556. assert.NoError(t, err)
  557. body := wire.SNAC_0x04_0x07_ICBMChannelMsgToClient{
  558. ChannelID: wire.ICBMChannelIM,
  559. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  560. }
  561. body.Append(wire.NewTLVBE(wire.ICBMTLVAOLIMData, frags))
  562. sess.handleIncomingIM(wire.SNACMessage{Body: body})
  563. events := sess.EventQueue.GetAllEvents()
  564. require.Len(t, events, 2)
  565. imEvent := events[0].Data.(types.IMEvent)
  566. assert.Equal(t, "mikekelly", imEvent.Source.AimID)
  567. assert.Equal(t, "Mike Kelly", imEvent.Source.DisplayID)
  568. convData := events[1].Data.(map[string]interface{})
  569. entries := convData["conversations"].([]map[string]interface{})
  570. require.Len(t, entries, 1)
  571. assert.Equal(t, "mikekelly", entries[0]["aimId"])
  572. assert.Equal(t, "Mike Kelly", entries[0]["displayId"])
  573. assert.Equal(t, "mikekelly", entries[0]["lastIM"].(map[string]interface{})["sender"])
  574. // The IM log is keyed by aimId, so the conversation the client opens from
  575. // this event finds its own history.
  576. msgs := sess.GetStoredIMs(StoredIMQuery{PartnerAimID: "mikekelly", NToGet: 10})
  577. require.Len(t, msgs, 1)
  578. assert.Equal(t, "hello", msgs[0]["message"])
  579. }
  580. func TestWebAPISession_HandleTypingNotification_NormalizesAimID(t *testing.T) {
  581. sess := &WebAPISession{
  582. Events: []string{"typing"},
  583. EventQueue: types.NewEventQueue(10),
  584. }
  585. sess.handleTypingNotification(wire.SNACMessage{
  586. Body: wire.SNAC_0x04_0x14_ICBMClientEvent{
  587. ScreenName: "Mike Kelly",
  588. Event: 0x0002,
  589. },
  590. })
  591. events := sess.EventQueue.GetAllEvents()
  592. require.Len(t, events, 1)
  593. typing := events[0].Data.(types.TypingEvent)
  594. assert.Equal(t, "mikekelly", typing.AimID)
  595. assert.Equal(t, "typing", typing.TypingStatus)
  596. }
  597. func TestWebAPISession_HandleBuddyArrivedDeparted_NormalizesAimID(t *testing.T) {
  598. sess := &WebAPISession{
  599. Events: []string{"presence"},
  600. EventQueue: types.NewEventQueue(10),
  601. }
  602. sess.handleBuddyArrived(wire.SNACMessage{
  603. Body: wire.SNAC_0x03_0x0B_BuddyArrived{
  604. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  605. },
  606. })
  607. sess.handleBuddyDeparted(wire.SNACMessage{
  608. Body: wire.SNAC_0x03_0x0C_BuddyDeparted{
  609. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  610. },
  611. })
  612. events := sess.EventQueue.GetAllEvents()
  613. require.Len(t, events, 2)
  614. arrived := events[0].Data.(types.PresenceEvent)
  615. assert.Equal(t, "mikekelly", arrived.AimID)
  616. assert.Equal(t, "online", arrived.State)
  617. departed := events[1].Data.(types.PresenceEvent)
  618. assert.Equal(t, "mikekelly", departed.AimID)
  619. assert.Equal(t, "offline", departed.State)
  620. }
  621. // A BuddyArrived carries the buddy's current icon as TLV 0x1D, so an icon change
  622. // rides along on the presence broadcast and must reach the presence event. The
  623. // stub BuddyIconURL stands in for the handlers-side URL formatter, which state
  624. // cannot import.
  625. func TestWebAPISession_PublishesBuddyIconOnPresence(t *testing.T) {
  626. newSession := func() *WebAPISession {
  627. return &WebAPISession{
  628. ScreenName: DisplayScreenName("me"),
  629. Events: []string{"presence"},
  630. EventQueue: types.NewEventQueue(10),
  631. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  632. BuddyIconURL: func(sn IdentScreenName, hash []byte) string {
  633. if len(hash) == 0 {
  634. return "placeholder:" + sn.String()
  635. }
  636. return "icon:" + hex.EncodeToString(hash)
  637. },
  638. }
  639. }
  640. arrived := func(sess *WebAPISession, screenName string, hash []byte) {
  641. info := wire.TLVUserInfo{ScreenName: screenName}
  642. if hash != nil {
  643. info.Append(wire.NewTLVBE(wire.OServiceUserInfoBARTInfo, wire.BARTID{
  644. Type: wire.BARTTypesBuddyIcon,
  645. BARTInfo: wire.BARTInfo{Hash: hash},
  646. }))
  647. }
  648. sess.handleBuddyArrived(wire.SNACMessage{Body: wire.SNAC_0x03_0x0B_BuddyArrived{TLVUserInfo: info}})
  649. }
  650. lastPresence := func(sess *WebAPISession) types.PresenceEvent {
  651. events := sess.EventQueue.GetAllEvents()
  652. require.Len(t, events, 1)
  653. return events[0].Data.(types.PresenceEvent)
  654. }
  655. t.Run("icon hash yields the content-addressed URL", func(t *testing.T) {
  656. sess := newSession()
  657. arrived(sess, "Mike Kelly", []byte{0xde, 0xad, 0xbe, 0xef})
  658. assert.Equal(t, "icon:deadbeef", lastPresence(sess).BuddyIcon)
  659. })
  660. t.Run("no icon TLV yields the placeholder URL", func(t *testing.T) {
  661. sess := newSession()
  662. arrived(sess, "Mike Kelly", nil)
  663. assert.Equal(t, "placeholder:mikekelly", lastPresence(sess).BuddyIcon)
  664. })
  665. t.Run("cleared icon yields a URL naming the sentinel hash", func(t *testing.T) {
  666. sess := newSession()
  667. arrived(sess, "Mike Kelly", wire.GetClearIconHash())
  668. assert.Equal(t, "icon:"+hex.EncodeToString(wire.GetClearIconHash()), lastPresence(sess).BuddyIcon)
  669. })
  670. t.Run("departed omits the icon so the client preserves it", func(t *testing.T) {
  671. sess := newSession()
  672. sess.handleBuddyDeparted(wire.SNACMessage{Body: wire.SNAC_0x03_0x0C_BuddyDeparted{
  673. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  674. }})
  675. assert.Empty(t, lastPresence(sess).BuddyIcon)
  676. })
  677. t.Run("no callback wired omits the icon", func(t *testing.T) {
  678. sess := newSession()
  679. sess.BuddyIconURL = nil
  680. arrived(sess, "Mike Kelly", []byte{0x01})
  681. assert.Empty(t, lastPresence(sess).BuddyIcon)
  682. })
  683. }
  684. // A user's own icon change is relayed to their session as OServiceUserInfoUpdate,
  685. // which the pump turns into a myInfo event so the identity badge re-renders.
  686. func TestWebAPISession_PushesMyInfoOnUserInfoUpdate(t *testing.T) {
  687. newSession := func(events ...string) (*WebAPISession, *int) {
  688. var refreshes int
  689. return &WebAPISession{
  690. ScreenName: DisplayScreenName("me"),
  691. Events: events,
  692. EventQueue: types.NewEventQueue(10),
  693. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  694. MyInfoRefresher: func(_ context.Context) (interface{}, error) {
  695. refreshes++
  696. return map[string]interface{}{"aimId": "me", "buddyIcon": "icon:new"}, nil
  697. },
  698. }, &refreshes
  699. }
  700. userInfoUpdate := wire.SNACMessage{Frame: wire.SNACFrame{
  701. FoodGroup: wire.OService,
  702. SubGroup: wire.OServiceUserInfoUpdate,
  703. }}
  704. t.Run("subscribed session gets one myInfo event", func(t *testing.T) {
  705. sess, refreshes := newSession("myInfo")
  706. sess.handleSNACMessage(userInfoUpdate)
  707. events := sess.EventQueue.GetAllEvents()
  708. require.Len(t, events, 1)
  709. assert.Equal(t, "myInfo", string(events[0].Type))
  710. assert.Equal(t, "icon:new", events[0].Data.(map[string]interface{})["buddyIcon"])
  711. assert.Equal(t, 1, *refreshes)
  712. })
  713. t.Run("a presence subscription also delivers myInfo", func(t *testing.T) {
  714. sess, _ := newSession("presence")
  715. sess.handleSNACMessage(userInfoUpdate)
  716. assert.Len(t, sess.EventQueue.GetAllEvents(), 1)
  717. })
  718. t.Run("unsubscribed session gets nothing and does not refresh", func(t *testing.T) {
  719. sess, refreshes := newSession("im")
  720. sess.handleSNACMessage(userInfoUpdate)
  721. assert.Empty(t, sess.EventQueue.GetAllEvents())
  722. assert.Equal(t, 0, *refreshes)
  723. })
  724. t.Run("other OService subgroups are ignored", func(t *testing.T) {
  725. sess, refreshes := newSession("myInfo")
  726. sess.handleSNACMessage(wire.SNACMessage{Frame: wire.SNACFrame{
  727. FoodGroup: wire.OService,
  728. SubGroup: wire.OServiceRateParamsQuery,
  729. }})
  730. assert.Empty(t, sess.EventQueue.GetAllEvents())
  731. assert.Equal(t, 0, *refreshes)
  732. })
  733. }
  734. // TestWebAPISessionManager_ShutdownBoundedByContext verifies that Shutdown
  735. // honors its context instead of blocking indefinitely. A listener goroutine that
  736. // ignores cancellation must not be able to hold the whole server open: main
  737. // budgets a few seconds for every server's shutdown combined, so an unbounded
  738. // wait here means the process never exits.
  739. func TestWebAPISessionManager_ShutdownBoundedByContext(t *testing.T) {
  740. mgr := NewWebAPISessionManager()
  741. inst := NewSession().AddInstance()
  742. sess, err := mgr.CreateSession("alice", "dev", []string{"presence"}, inst, "", slog.Default())
  743. assert.NoError(t, err)
  744. // Stand in for a listener wedged somewhere that never observes cancellation.
  745. release := make(chan struct{})
  746. defer close(release)
  747. sess.listeners.Add(1)
  748. go func() {
  749. defer sess.listeners.Done()
  750. <-release
  751. }()
  752. ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
  753. defer cancel()
  754. start := time.Now()
  755. err = mgr.Shutdown(ctx)
  756. elapsed := time.Since(start)
  757. assert.ErrorIs(t, err, context.DeadlineExceeded)
  758. assert.Less(t, elapsed, 2*time.Second, "Shutdown must give up at its deadline, not wait on the stuck listener")
  759. }
  760. // TestWebAPISession_CloseCancelsSessionContext verifies that Close cancels the
  761. // context handed to the refresher callbacks. The listener runs feedbag queries
  762. // through it, and without cancellation Close's wait lasts as long as the query.
  763. func TestWebAPISession_CloseCancelsSessionContext(t *testing.T) {
  764. mgr := NewWebAPISessionManager()
  765. inst := NewSession().AddInstance()
  766. sess, err := mgr.CreateSession("alice", "dev", []string{"presence"}, inst, "", slog.Default())
  767. assert.NoError(t, err)
  768. assert.NoError(t, sess.ctx.Err(), "session context should be live before Close")
  769. sess.Close()
  770. assert.ErrorIs(t, sess.ctx.Err(), context.Canceled)
  771. }