webapi_session_test.go 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070
  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.(map[string]interface{})
  724. entries := convData["conversations"].([]map[string]interface{})
  725. require.Len(t, entries, 1)
  726. assert.Equal(t, "mikekelly", entries[0]["aimId"])
  727. assert.Equal(t, "Mike Kelly", entries[0]["displayId"])
  728. assert.Equal(t, "mikekelly", entries[0]["lastIM"].(map[string]interface{})["sender"])
  729. // The IM log is keyed by aimId, so the conversation the client opens from
  730. // this event finds its own history.
  731. msgs := sess.GetStoredIMs(StoredIMQuery{PartnerAimID: "mikekelly", NToGet: 10})
  732. require.Len(t, msgs, 1)
  733. assert.Equal(t, "hello", msgs[0]["message"])
  734. }
  735. func TestWebAPISession_HandleTypingNotification_NormalizesAimID(t *testing.T) {
  736. sess := &WebAPISession{
  737. Events: []string{"typing"},
  738. EventQueue: types.NewEventQueue(10),
  739. }
  740. sess.handleTypingNotification(wire.SNACMessage{
  741. Body: wire.SNAC_0x04_0x14_ICBMClientEvent{
  742. ScreenName: "Mike Kelly",
  743. Event: 0x0002,
  744. },
  745. })
  746. events := sess.EventQueue.GetAllEvents()
  747. require.Len(t, events, 1)
  748. typing := events[0].Data.(types.TypingEvent)
  749. assert.Equal(t, "mikekelly", typing.AimID)
  750. assert.Equal(t, "typing", typing.TypingStatus)
  751. }
  752. func TestWebAPISession_HandleBuddyArrivedDeparted_NormalizesAimID(t *testing.T) {
  753. sess := &WebAPISession{
  754. Events: []string{"presence"},
  755. EventQueue: types.NewEventQueue(10),
  756. }
  757. sess.handleBuddyArrived(wire.SNACMessage{
  758. Body: wire.SNAC_0x03_0x0B_BuddyArrived{
  759. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  760. },
  761. })
  762. sess.handleBuddyDeparted(wire.SNACMessage{
  763. Body: wire.SNAC_0x03_0x0C_BuddyDeparted{
  764. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  765. },
  766. })
  767. events := sess.EventQueue.GetAllEvents()
  768. require.Len(t, events, 2)
  769. arrived := events[0].Data.(types.PresenceEvent)
  770. assert.Equal(t, "mikekelly", arrived.AimID)
  771. assert.Equal(t, "online", arrived.State)
  772. departed := events[1].Data.(types.PresenceEvent)
  773. assert.Equal(t, "mikekelly", departed.AimID)
  774. assert.Equal(t, "offline", departed.State)
  775. }
  776. // A BuddyArrived carries the buddy's current icon as TLV 0x1D, so an icon change
  777. // rides along on the presence broadcast and must reach the presence event. The
  778. // stub BuddyIconURL stands in for the handlers-side URL formatter, which state
  779. // cannot import.
  780. func TestWebAPISession_PublishesBuddyIconOnPresence(t *testing.T) {
  781. newSession := func() *WebAPISession {
  782. return &WebAPISession{
  783. ScreenName: DisplayScreenName("me"),
  784. Events: []string{"presence"},
  785. EventQueue: types.NewEventQueue(10),
  786. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  787. BuddyIconURL: func(sn IdentScreenName, hash []byte) string {
  788. if len(hash) == 0 {
  789. return "placeholder:" + sn.String()
  790. }
  791. return "icon:" + hex.EncodeToString(hash)
  792. },
  793. }
  794. }
  795. arrived := func(sess *WebAPISession, screenName string, hash []byte) {
  796. info := wire.TLVUserInfo{ScreenName: screenName}
  797. if hash != nil {
  798. info.Append(wire.NewTLVBE(wire.OServiceUserInfoBARTInfo, wire.BARTID{
  799. Type: wire.BARTTypesBuddyIcon,
  800. BARTInfo: wire.BARTInfo{Hash: hash},
  801. }))
  802. }
  803. sess.handleBuddyArrived(wire.SNACMessage{Body: wire.SNAC_0x03_0x0B_BuddyArrived{TLVUserInfo: info}})
  804. }
  805. lastPresence := func(sess *WebAPISession) types.PresenceEvent {
  806. events := sess.EventQueue.GetAllEvents()
  807. require.Len(t, events, 1)
  808. return events[0].Data.(types.PresenceEvent)
  809. }
  810. t.Run("icon hash yields the content-addressed URL", func(t *testing.T) {
  811. sess := newSession()
  812. arrived(sess, "Mike Kelly", []byte{0xde, 0xad, 0xbe, 0xef})
  813. assert.Equal(t, "icon:deadbeef", lastPresence(sess).BuddyIcon)
  814. })
  815. t.Run("no icon TLV yields the placeholder URL", func(t *testing.T) {
  816. sess := newSession()
  817. arrived(sess, "Mike Kelly", nil)
  818. assert.Equal(t, "placeholder:mikekelly", lastPresence(sess).BuddyIcon)
  819. })
  820. t.Run("cleared icon yields a URL naming the sentinel hash", func(t *testing.T) {
  821. sess := newSession()
  822. arrived(sess, "Mike Kelly", wire.GetClearIconHash())
  823. assert.Equal(t, "icon:"+hex.EncodeToString(wire.GetClearIconHash()), lastPresence(sess).BuddyIcon)
  824. })
  825. t.Run("departed omits the icon so the client preserves it", func(t *testing.T) {
  826. sess := newSession()
  827. sess.handleBuddyDeparted(wire.SNACMessage{Body: wire.SNAC_0x03_0x0C_BuddyDeparted{
  828. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  829. }})
  830. assert.Empty(t, lastPresence(sess).BuddyIcon)
  831. })
  832. t.Run("no callback wired omits the icon", func(t *testing.T) {
  833. sess := newSession()
  834. sess.BuddyIconURL = nil
  835. arrived(sess, "Mike Kelly", []byte{0x01})
  836. assert.Empty(t, lastPresence(sess).BuddyIcon)
  837. })
  838. }
  839. // A user's own icon change is relayed to their session as OServiceUserInfoUpdate,
  840. // which the pump turns into a myInfo event so the identity badge re-renders.
  841. func TestWebAPISession_PushesMyInfoOnUserInfoUpdate(t *testing.T) {
  842. newSession := func(events ...string) (*WebAPISession, *int) {
  843. var refreshes int
  844. return &WebAPISession{
  845. ScreenName: DisplayScreenName("me"),
  846. Events: events,
  847. EventQueue: types.NewEventQueue(10),
  848. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  849. MyInfoRefresher: func(_ context.Context) (interface{}, error) {
  850. refreshes++
  851. return map[string]interface{}{"aimId": "me", "buddyIcon": "icon:new"}, nil
  852. },
  853. }, &refreshes
  854. }
  855. userInfoUpdate := wire.SNACMessage{Frame: wire.SNACFrame{
  856. FoodGroup: wire.OService,
  857. SubGroup: wire.OServiceUserInfoUpdate,
  858. }}
  859. t.Run("subscribed session gets one myInfo event", func(t *testing.T) {
  860. sess, refreshes := newSession("myInfo")
  861. sess.handleSNACMessage(userInfoUpdate)
  862. events := sess.EventQueue.GetAllEvents()
  863. require.Len(t, events, 1)
  864. assert.Equal(t, "myInfo", string(events[0].Type))
  865. assert.Equal(t, "icon:new", events[0].Data.(map[string]interface{})["buddyIcon"])
  866. assert.Equal(t, 1, *refreshes)
  867. })
  868. t.Run("a presence subscription also delivers myInfo", func(t *testing.T) {
  869. sess, _ := newSession("presence")
  870. sess.handleSNACMessage(userInfoUpdate)
  871. assert.Len(t, sess.EventQueue.GetAllEvents(), 1)
  872. })
  873. t.Run("unsubscribed session gets nothing and does not refresh", func(t *testing.T) {
  874. sess, refreshes := newSession("im")
  875. sess.handleSNACMessage(userInfoUpdate)
  876. assert.Empty(t, sess.EventQueue.GetAllEvents())
  877. assert.Equal(t, 0, *refreshes)
  878. })
  879. t.Run("other OService subgroups are ignored", func(t *testing.T) {
  880. sess, refreshes := newSession("myInfo")
  881. sess.handleSNACMessage(wire.SNACMessage{Frame: wire.SNACFrame{
  882. FoodGroup: wire.OService,
  883. SubGroup: wire.OServiceRateParamsQuery,
  884. }})
  885. assert.Empty(t, sess.EventQueue.GetAllEvents())
  886. assert.Equal(t, 0, *refreshes)
  887. })
  888. }
  889. // TestWebAPISessionManager_ShutdownBoundedByContext verifies that Shutdown
  890. // honors its context instead of blocking indefinitely. A listener goroutine that
  891. // ignores cancellation must not be able to hold the whole server open: main
  892. // budgets a few seconds for every server's shutdown combined, so an unbounded
  893. // wait here means the process never exits.
  894. func TestWebAPISessionManager_ShutdownBoundedByContext(t *testing.T) {
  895. mgr := NewWebAPISessionManager()
  896. inst := NewSession().AddInstance()
  897. sess, err := mgr.CreateSession("alice", "dev", []string{"presence"}, inst, "", slog.Default())
  898. assert.NoError(t, err)
  899. // Stand in for a listener wedged somewhere that never observes cancellation.
  900. release := make(chan struct{})
  901. defer close(release)
  902. sess.listeners.Add(1)
  903. go func() {
  904. defer sess.listeners.Done()
  905. <-release
  906. }()
  907. ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
  908. defer cancel()
  909. start := time.Now()
  910. err = mgr.Shutdown(ctx)
  911. elapsed := time.Since(start)
  912. assert.ErrorIs(t, err, context.DeadlineExceeded)
  913. assert.Less(t, elapsed, 2*time.Second, "Shutdown must give up at its deadline, not wait on the stuck listener")
  914. }
  915. // TestWebAPISession_CloseCancelsSessionContext verifies that Close cancels the
  916. // context handed to the refresher callbacks. The listener runs feedbag queries
  917. // through it, and without cancellation Close's wait lasts as long as the query.
  918. func TestWebAPISession_CloseCancelsSessionContext(t *testing.T) {
  919. mgr := NewWebAPISessionManager()
  920. inst := NewSession().AddInstance()
  921. sess, err := mgr.CreateSession("alice", "dev", []string{"presence"}, inst, "", slog.Default())
  922. assert.NoError(t, err)
  923. assert.NoError(t, sess.ctx.Err(), "session context should be live before Close")
  924. sess.Close()
  925. assert.ErrorIs(t, sess.ctx.Err(), context.Canceled)
  926. }