session_test.go 53 KB

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