session_test.go 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449
  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. func TestSession_PublishesBuddyIconOnPresence(t *testing.T) {
  600. newSession := func() *Session {
  601. return &Session{
  602. ScreenName: state.DisplayScreenName("me"),
  603. Events: []string{"presence"},
  604. EventQueue: NewEventQueue(10),
  605. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  606. BuddyIconURL: func(sn state.IdentScreenName, hash []byte) string {
  607. if len(hash) == 0 {
  608. return "placeholder:" + sn.String()
  609. }
  610. return "icon:" + hex.EncodeToString(hash)
  611. },
  612. }
  613. }
  614. arrived := func(sess *Session, screenName string, hash []byte) {
  615. info := wire.TLVUserInfo{ScreenName: screenName}
  616. if hash != nil {
  617. info.Append(wire.NewTLVBE(wire.OServiceUserInfoBARTInfo, wire.BARTID{
  618. Type: wire.BARTTypesBuddyIcon,
  619. BARTInfo: wire.BARTInfo{Hash: hash},
  620. }))
  621. }
  622. sess.handleBuddyArrived(wire.SNACMessage{Body: wire.SNAC_0x03_0x0B_BuddyArrived{TLVUserInfo: info}})
  623. }
  624. lastPresence := func(sess *Session) PresenceEvent {
  625. events := sess.EventQueue.GetAllEvents()
  626. require.Len(t, events, 1)
  627. return events[0].Data.(PresenceEvent)
  628. }
  629. t.Run("icon hash yields the content-addressed URL", func(t *testing.T) {
  630. sess := newSession()
  631. arrived(sess, "Mike Kelly", []byte{0xde, 0xad, 0xbe, 0xef})
  632. assert.Equal(t, "icon:deadbeef", lastPresence(sess).BuddyIcon)
  633. })
  634. t.Run("no icon TLV yields the placeholder URL", func(t *testing.T) {
  635. sess := newSession()
  636. arrived(sess, "Mike Kelly", nil)
  637. assert.Equal(t, "placeholder:mikekelly", lastPresence(sess).BuddyIcon)
  638. })
  639. t.Run("cleared icon yields a URL naming the sentinel hash", func(t *testing.T) {
  640. sess := newSession()
  641. arrived(sess, "Mike Kelly", wire.GetClearIconHash())
  642. assert.Equal(t, "icon:"+hex.EncodeToString(wire.GetClearIconHash()), lastPresence(sess).BuddyIcon)
  643. })
  644. t.Run("departed omits the icon so the client preserves it", func(t *testing.T) {
  645. sess := newSession()
  646. sess.handleBuddyDeparted(wire.SNACMessage{Body: wire.SNAC_0x03_0x0C_BuddyDeparted{
  647. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  648. }})
  649. assert.Empty(t, lastPresence(sess).BuddyIcon)
  650. })
  651. t.Run("no callback wired omits the icon", func(t *testing.T) {
  652. sess := newSession()
  653. sess.BuddyIconURL = nil
  654. arrived(sess, "Mike Kelly", []byte{0x01})
  655. assert.Empty(t, lastPresence(sess).BuddyIcon)
  656. })
  657. }
  658. // A change to a user's own info is relayed to their session as
  659. // OServiceUserInfoUpdate, which the pump turns into a myInfo event so the
  660. // identity badge re-renders.
  661. func TestSession_PushesMyInfoOnUserInfoUpdate(t *testing.T) {
  662. newSession := func(events ...string) *Session {
  663. return &Session{
  664. ScreenName: state.DisplayScreenName("me"),
  665. OSCARSession: state.NewSession().AddInstance(),
  666. BaseURL: "http://api.example.com",
  667. Events: events,
  668. EventQueue: NewEventQueue(10),
  669. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  670. BuddyIconURL: func(sn state.IdentScreenName, hash []byte) string {
  671. if len(hash) == 0 {
  672. return "placeholder:" + sn.String()
  673. }
  674. return "icon:" + hex.EncodeToString(hash)
  675. },
  676. }
  677. }
  678. update := func(info wire.TLVUserInfo) wire.SNACMessage {
  679. return wire.SNACMessage{
  680. Frame: wire.SNACFrame{
  681. FoodGroup: wire.OService,
  682. SubGroup: wire.OServiceUserInfoUpdate,
  683. },
  684. Body: wire.SNAC_0x01_0x0F_OServiceUserInfoUpdate{
  685. UserInfo: []wire.TLVUserInfo{info},
  686. },
  687. }
  688. }
  689. lastMyInfo := func(t *testing.T, sess *Session) *MyInfo {
  690. t.Helper()
  691. events := sess.EventQueue.GetAllEvents()
  692. require.Len(t, events, 1)
  693. require.Equal(t, EventTypeMyInfo, events[0].Type)
  694. return events[0].Data.(*MyInfo)
  695. }
  696. t.Run("subscribed session gets one myInfo built from the SNAC", func(t *testing.T) {
  697. sess := newSession("myInfo")
  698. sess.handleSNACMessage(update(wire.TLVUserInfo{ScreenName: "Mike Kelly"}))
  699. myInfo := lastMyInfo(t, sess)
  700. assert.Equal(t, "mikekelly", myInfo.AimID)
  701. assert.Equal(t, "Mike Kelly", myInfo.DisplayID)
  702. assert.Equal(t, "Mike Kelly", myInfo.Friendly)
  703. assert.Equal(t, "online", myInfo.State)
  704. })
  705. t.Run("a presence subscription also delivers myInfo", func(t *testing.T) {
  706. sess := newSession("presence")
  707. sess.handleSNACMessage(update(wire.TLVUserInfo{ScreenName: "me"}))
  708. assert.Len(t, sess.EventQueue.GetAllEvents(), 1)
  709. })
  710. t.Run("unsubscribed session gets nothing", func(t *testing.T) {
  711. sess := newSession("im")
  712. sess.handleSNACMessage(update(wire.TLVUserInfo{ScreenName: "me"}))
  713. assert.Empty(t, sess.EventQueue.GetAllEvents())
  714. })
  715. t.Run("other OService subgroups are ignored", func(t *testing.T) {
  716. sess := newSession("myInfo")
  717. sess.handleSNACMessage(wire.SNACMessage{Frame: wire.SNACFrame{
  718. FoodGroup: wire.OService,
  719. SubGroup: wire.OServiceRateParamsQuery,
  720. }})
  721. assert.Empty(t, sess.EventQueue.GetAllEvents())
  722. })
  723. t.Run("an update carrying no user info block pushes nothing", func(t *testing.T) {
  724. sess := newSession("myInfo")
  725. sess.handleSNACMessage(wire.SNACMessage{
  726. Frame: wire.SNACFrame{
  727. FoodGroup: wire.OService,
  728. SubGroup: wire.OServiceUserInfoUpdate,
  729. },
  730. Body: wire.SNAC_0x01_0x0F_OServiceUserInfoUpdate{},
  731. })
  732. assert.Empty(t, sess.EventQueue.GetAllEvents())
  733. })
  734. t.Run("the away message comes from the session", func(t *testing.T) {
  735. sess := newSession("myInfo")
  736. // Session.AwayMessage reads only instances that are actually away.
  737. sess.OSCARSession.SetUserInfoFlag(wire.OServiceUserFlagUnavailable)
  738. sess.OSCARSession.SetAwayMessage("brb")
  739. info := wire.TLVUserInfo{ScreenName: "me"}
  740. info.Append(wire.NewTLVBE(wire.OServiceUserInfoUserFlags, wire.OServiceUserFlagUnavailable))
  741. sess.handleSNACMessage(update(info))
  742. myInfo := lastMyInfo(t, sess)
  743. assert.Equal(t, "away", myInfo.State)
  744. assert.Equal(t, "brb", myInfo.AwayMsg)
  745. })
  746. t.Run("a mood capability publishes its icon", func(t *testing.T) {
  747. sess := newSession("myInfo")
  748. info := wire.TLVUserInfo{ScreenName: "me"}
  749. info.Append(wire.NewTLVBE(wire.OServiceUserInfoOscarCaps, wire.CapXStatusPlate[:]))
  750. sess.handleSNACMessage(update(info))
  751. assert.Equal(t, "http://api.example.com/mood?id="+wire.MoodIconID("0icqmood6"), lastMyInfo(t, sess).MoodIcon)
  752. })
  753. t.Run("the icon hash yields the content-addressed URL", func(t *testing.T) {
  754. sess := newSession("myInfo")
  755. info := wire.TLVUserInfo{ScreenName: "me"}
  756. info.Append(wire.NewTLVBE(wire.OServiceUserInfoBARTInfo, wire.BARTID{
  757. Type: wire.BARTTypesBuddyIcon,
  758. BARTInfo: wire.BARTInfo{Hash: []byte{0xde, 0xad, 0xbe, 0xef}},
  759. }))
  760. sess.handleSNACMessage(update(info))
  761. assert.Equal(t, "icon:deadbeef", lastMyInfo(t, sess).BuddyIcon)
  762. })
  763. t.Run("no icon TLV yields the placeholder URL, which clears a removed icon", func(t *testing.T) {
  764. sess := newSession("myInfo")
  765. sess.handleSNACMessage(update(wire.TLVUserInfo{ScreenName: "me"}))
  766. assert.Equal(t, "placeholder:me", lastMyInfo(t, sess).BuddyIcon)
  767. })
  768. t.Run("the state is read off the user info block", func(t *testing.T) {
  769. tests := []struct {
  770. name string
  771. screenName string
  772. flags uint16
  773. status uint32
  774. idle uint16
  775. want string
  776. }{
  777. {name: "invisible", screenName: "me", status: wire.OServiceUserStatusInvisible, want: "invisible"},
  778. {name: "icq busy", screenName: "100003", status: wire.OServiceUserStatusBusy, want: "occupied"},
  779. {name: "aim busy reports away", screenName: "me", status: wire.OServiceUserStatusBusy, want: "away"},
  780. {name: "icq dnd", screenName: "100003", status: wire.OServiceUserStatusDND, want: "dnd"},
  781. {name: "away flag", screenName: "me", flags: wire.OServiceUserFlagUnavailable, want: "away"},
  782. {name: "away status bit", screenName: "me", status: wire.OServiceUserStatusAway, want: "away"},
  783. {name: "idle", screenName: "me", idle: 5, want: "idle"},
  784. {name: "nothing set", screenName: "me", want: "online"},
  785. }
  786. for _, tt := range tests {
  787. t.Run(tt.name, func(t *testing.T) {
  788. sess := newSession("myInfo")
  789. info := wire.TLVUserInfo{ScreenName: tt.screenName}
  790. info.Append(wire.NewTLVBE(wire.OServiceUserInfoUserFlags, tt.flags))
  791. info.Append(wire.NewTLVBE(wire.OServiceUserInfoStatus, tt.status))
  792. if tt.idle > 0 {
  793. info.Append(wire.NewTLVBE(wire.OServiceUserInfoIdleTime, tt.idle))
  794. }
  795. sess.handleSNACMessage(update(info))
  796. assert.Equal(t, tt.want, lastMyInfo(t, sess).State)
  797. })
  798. }
  799. })
  800. }
  801. // TestSessionManager_ShutdownBoundedByContext verifies that Shutdown
  802. // honors its context instead of blocking indefinitely. A listener goroutine that
  803. // ignores cancellation must not be able to hold the whole server open: main
  804. // budgets a few seconds for every server's shutdown combined, so an unbounded
  805. // wait here means the process never exits.
  806. func TestSessionManager_ShutdownBoundedByContext(t *testing.T) {
  807. mgr := NewSessionManager()
  808. inst := state.NewSession().AddInstance()
  809. sess, err := mgr.CreateSession("alice", []string{"presence"}, inst, "", slog.Default())
  810. assert.NoError(t, err)
  811. // Stand in for a listener wedged somewhere that never observes cancellation.
  812. release := make(chan struct{})
  813. defer close(release)
  814. sess.listeners.Go(func() {
  815. <-release
  816. })
  817. ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
  818. defer cancel()
  819. start := time.Now()
  820. err = mgr.Shutdown(ctx)
  821. elapsed := time.Since(start)
  822. assert.ErrorIs(t, err, context.DeadlineExceeded)
  823. assert.Less(t, elapsed, 2*time.Second, "Shutdown must give up at its deadline, not wait on the stuck listener")
  824. }
  825. // TestSession_CloseCancelsSessionContext verifies that Close cancels the
  826. // context handed to the refresher callbacks. The listener runs feedbag queries
  827. // through it, and without cancellation Close's wait lasts as long as the query.
  828. func TestSession_CloseCancelsSessionContext(t *testing.T) {
  829. mgr := NewSessionManager()
  830. inst := state.NewSession().AddInstance()
  831. sess, err := mgr.CreateSession("alice", []string{"presence"}, inst, "", slog.Default())
  832. assert.NoError(t, err)
  833. assert.NoError(t, sess.ctx.Err(), "session context should be live before Close")
  834. sess.Close()
  835. assert.ErrorIs(t, sess.ctx.Err(), context.Canceled)
  836. }
  837. // A message replayed out of the offline store arrives as an ordinary
  838. // ICBMChannelMsgToClient stamped with a send time. The client models that as its
  839. // own offlineIM event, keyed by a bare aimId and timestamped when the sender sent
  840. // it rather than when it was delivered.
  841. func TestSession_OfflineIM(t *testing.T) {
  842. sentAt := time.Now().Add(-2 * time.Hour).Unix()
  843. newSession := func(events ...string) *Session {
  844. return &Session{
  845. ScreenName: state.DisplayScreenName("me"),
  846. Events: events,
  847. EventQueue: NewEventQueue(10),
  848. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  849. }
  850. }
  851. storedMsg := func(t *testing.T, withSendTime bool) wire.SNACMessage {
  852. t.Helper()
  853. frags, err := wire.ICBMFragmentList("sent while you were out")
  854. require.NoError(t, err)
  855. body := wire.SNAC_0x04_0x07_ICBMChannelMsgToClient{
  856. ChannelID: wire.ICBMChannelIM,
  857. TLVUserInfo: wire.TLVUserInfo{ScreenName: "Mike Kelly"},
  858. }
  859. body.Append(wire.NewTLVBE(wire.ICBMTLVAOLIMData, frags))
  860. if withSendTime {
  861. body.Append(wire.NewTLVBE(wire.ICBMTLVSendTime, uint32(sentAt)))
  862. }
  863. return wire.SNACMessage{Body: body}
  864. }
  865. t.Run("send time yields an offlineIM event", func(t *testing.T) {
  866. sess := newSession("im", "offlineIM")
  867. sess.handleIncomingIM(storedMsg(t, true))
  868. events := sess.EventQueue.GetAllEvents()
  869. require.Len(t, events, 1)
  870. assert.Equal(t, EventTypeOfflineIM, events[0].Type)
  871. offline := events[0].Data.(OfflineIMEvent)
  872. assert.Equal(t, "mikekelly", offline.AimID)
  873. assert.Equal(t, "sent while you were out", offline.Message)
  874. assert.NotEmpty(t, offline.MsgID)
  875. assert.Equal(t, int64(sentAt), offline.Timestamp)
  876. })
  877. t.Run("no send time yields an im event", func(t *testing.T) {
  878. sess := newSession("im", "offlineIM")
  879. sess.handleIncomingIM(storedMsg(t, false))
  880. events := sess.EventQueue.GetAllEvents()
  881. require.Len(t, events, 1)
  882. assert.Equal(t, EventTypeIM, events[0].Type)
  883. })
  884. t.Run("offlineIM subscriber gets a conversation update", func(t *testing.T) {
  885. sess := newSession("offlineIM", "conversation")
  886. sess.handleIncomingIM(storedMsg(t, true))
  887. events := sess.EventQueue.GetAllEvents()
  888. require.Len(t, events, 2)
  889. assert.Equal(t, EventTypeOfflineIM, events[0].Type)
  890. assert.Equal(t, EventTypeConversation, events[1].Type)
  891. })
  892. // The history the client pulls with fetchStoredIMs has to order the message by
  893. // when it was sent, not when the session that drained the store started.
  894. t.Run("logs the message under its send time", func(t *testing.T) {
  895. sess := newSession("offlineIM")
  896. sess.handleIncomingIM(storedMsg(t, true))
  897. stored := sess.GetStoredIMs(StoredIMQuery{PartnerAimID: "mikekelly", NToGet: 10})
  898. require.Len(t, stored, 1)
  899. assert.Equal(t, int64(sentAt), stored[0].Date)
  900. })
  901. // Only a live IM is filtered on subscription here. Retrieval answers the
  902. // instance that asked and StartSession asks only for an offlineIM subscriber,
  903. // so a stamped message reaching a session that did not subscribe is not a state
  904. // this handler can be put in.
  905. t.Run("no subscription drops a live message", func(t *testing.T) {
  906. sess := newSession("presence")
  907. sess.handleIncomingIM(storedMsg(t, false))
  908. assert.Empty(t, sess.EventQueue.GetAllEvents())
  909. })
  910. }
  911. // A boot closes the account's OSCAR session out from under its web session. The
  912. // client is parked on a long poll at that moment, so it must be released with a
  913. // sessionEnded event rather than left to hang until the reaper's next sweep —
  914. // which measured 26-28s against a running server.
  915. func TestSession_BootReleasesParkedFetcherWithSessionEnded(t *testing.T) {
  916. mgr := NewSessionManager()
  917. inst := state.NewSession().AddInstance()
  918. sess, err := mgr.CreateSession(state.DisplayScreenName("mike"), []string{"presence"}, inst, "", slog.Default())
  919. require.NoError(t, err)
  920. sess.StartListeningToOSCARSession()
  921. // Park a fetcher the way fetchEvents does, with nothing pending.
  922. type result struct {
  923. events []Event
  924. err error
  925. }
  926. done := make(chan result, 1)
  927. go func() {
  928. events, err := sess.EventQueue.Fetch(context.Background(), 0, 60*time.Second)
  929. done <- result{events, err}
  930. }()
  931. // Let the fetcher block before the session is taken away.
  932. time.Sleep(50 * time.Millisecond)
  933. inst.Session().CloseSession()
  934. select {
  935. case got := <-done:
  936. require.NoError(t, got.err)
  937. require.Len(t, got.events, 1)
  938. assert.Equal(t, EventTypeSessionEnded, got.events[0].Type)
  939. case <-time.After(5 * time.Second):
  940. t.Fatal("parked fetcher was not released by the boot")
  941. }
  942. }
  943. // A session tearing itself down — endSession, or the idle reaper — needs no
  944. // sessionEnded event: the client already knows it is leaving. Close closes the
  945. // queue before the instance, so the listener's push lands on a closed queue.
  946. func TestSession_SelfCloseEmitsNoSessionEndedEvent(t *testing.T) {
  947. mgr := NewSessionManager()
  948. inst := state.NewSession().AddInstance()
  949. sess, err := mgr.CreateSession(state.DisplayScreenName("mike"), []string{"presence"}, inst, "", slog.Default())
  950. require.NoError(t, err)
  951. sess.StartListeningToOSCARSession()
  952. require.NoError(t, mgr.RemoveSession(context.Background(), sess.AimSID))
  953. events, err := sess.EventQueue.Fetch(context.Background(), 0, time.Second)
  954. require.NoError(t, err)
  955. assert.Empty(t, events)
  956. }
  957. func TestSession_GetStoredIMs(t *testing.T) {
  958. sess := &Session{}
  959. sess.AddStoredIM("buddy1", "me", "hello", "msg-1", 100)
  960. sess.AddStoredIM("buddy1", "buddy1", "hi back", "msg-2", 200)
  961. sess.AddStoredIM("buddy2", "buddy2", "other chat", "msg-3", 150)
  962. msgs := sess.GetStoredIMs(StoredIMQuery{
  963. PartnerAimID: "buddy1",
  964. SortOrder: "descendingDate",
  965. NToGet: 10,
  966. })
  967. assert.Len(t, msgs, 2)
  968. assert.Equal(t, "msg-2", msgs[0].MsgID)
  969. assert.Equal(t, int64(200), msgs[0].Date)
  970. assert.Equal(t, "hello", msgs[1].Message)
  971. msgs = sess.GetStoredIMs(StoredIMQuery{
  972. PartnerAimID: "buddy1",
  973. SortOrder: "ascendingDate",
  974. StartTime: 150,
  975. EndTime: 250,
  976. })
  977. assert.Len(t, msgs, 1)
  978. assert.Equal(t, "msg-2", msgs[0].MsgID)
  979. }
  980. func TestSession_GetStoredIMs_NormalizesPartner(t *testing.T) {
  981. sess := &Session{}
  982. sess.AddStoredIM("Mike Kelly", "mikekelly", "hello", "msg-1", 100)
  983. // The web client queries history by the normalized aimId, never by the
  984. // display screen name it was stored under.
  985. msgs := sess.GetStoredIMs(StoredIMQuery{
  986. PartnerAimID: "mikekelly",
  987. NToGet: 10,
  988. })
  989. require.Len(t, msgs, 1)
  990. assert.Equal(t, "msg-1", msgs[0].MsgID)
  991. }
  992. // A session gets no insert/update/delete SNAC for a feedbag change it made itself —
  993. // those reach only a user's *other* instances. FeedbagStatus is the one notification
  994. // it does receive, so it drives the roster event for the client's own edits.
  995. func TestSession_FeedbagStatusRefreshesBuddyList(t *testing.T) {
  996. tests := []struct {
  997. name string
  998. events []string
  999. results []uint16
  1000. body any
  1001. wantEvent bool
  1002. }{
  1003. {
  1004. name: "stored item refreshes the roster",
  1005. events: []string{"buddylist"},
  1006. results: []uint16{0x0000},
  1007. wantEvent: true,
  1008. },
  1009. {
  1010. // The declined item is still worth a refresh: the roster is how the
  1011. // client discovers the buddy was not stored, since it is absent from it.
  1012. name: "declined item still refreshes the roster",
  1013. events: []string{"buddylist"},
  1014. results: []uint16{feedbagResultAuthRequired},
  1015. wantEvent: true,
  1016. },
  1017. {
  1018. name: "no event when not subscribed",
  1019. events: []string{"presence"},
  1020. results: []uint16{0x0000},
  1021. wantEvent: false,
  1022. },
  1023. {
  1024. name: "a body of the wrong type still refreshes",
  1025. events: []string{"buddylist"},
  1026. body: wire.SNAC_0x13_0x06_FeedbagReply{},
  1027. wantEvent: true,
  1028. },
  1029. }
  1030. for _, tt := range tests {
  1031. t.Run(tt.name, func(t *testing.T) {
  1032. refreshed := 0
  1033. sess := &Session{
  1034. ScreenName: state.DisplayScreenName("me"),
  1035. Events: tt.events,
  1036. EventQueue: NewEventQueue(10),
  1037. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  1038. BuddyListRefresher: func(_ context.Context) (any, error) {
  1039. refreshed++
  1040. return &BuddyListData{Groups: []BuddyGroup{}}, nil
  1041. },
  1042. }
  1043. body := tt.body
  1044. if body == nil {
  1045. body = wire.SNAC_0x13_0x0E_FeedbagStatus{Results: tt.results}
  1046. }
  1047. sess.handleFeedbagMessage(wire.SNACMessage{
  1048. Frame: wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagStatus},
  1049. Body: body,
  1050. })
  1051. var got int
  1052. for _, event := range sess.EventQueue.GetAllEvents() {
  1053. if event.Type == EventTypeBuddyList {
  1054. got++
  1055. }
  1056. }
  1057. if tt.wantEvent {
  1058. assert.Equal(t, 1, got)
  1059. assert.Equal(t, 1, refreshed)
  1060. } else {
  1061. assert.Zero(t, got)
  1062. assert.Zero(t, refreshed, "an unsubscribed session should not even query the roster")
  1063. }
  1064. })
  1065. }
  1066. }
  1067. func TestSession_HandleClientError(t *testing.T) {
  1068. const (
  1069. cookie = uint64(0xDEADBEEFCAFEF00D)
  1070. msgID = "11112222-3333-4444-8000-555566667777"
  1071. )
  1072. tests := []struct {
  1073. name string
  1074. // events is what the session subscribed to at startSession.
  1075. events []string
  1076. // record seeds the cookie->msgId map the way a prior im/sendIM would.
  1077. record bool
  1078. channelID uint16
  1079. wantEvent bool
  1080. wantCooki string
  1081. wantChan string
  1082. }{
  1083. {
  1084. name: "im channel names the message this session sent",
  1085. events: []string{"im"},
  1086. record: true,
  1087. channelID: wire.ICBMChannelIM,
  1088. wantEvent: true,
  1089. wantCooki: msgID,
  1090. wantChan: "im",
  1091. },
  1092. {
  1093. name: "rendezvous channel is reported as data",
  1094. events: []string{"im"},
  1095. record: true,
  1096. channelID: wire.ICBMChannelRendezvous,
  1097. wantEvent: true,
  1098. wantCooki: msgID,
  1099. wantChan: "data",
  1100. },
  1101. {
  1102. // Another instance of the account sent the message, so this session
  1103. // has no msgId for it and must not invent one.
  1104. name: "unknown cookie yields an empty msgId",
  1105. events: []string{"im"},
  1106. record: false,
  1107. channelID: wire.ICBMChannelIM,
  1108. wantEvent: true,
  1109. wantCooki: "",
  1110. wantChan: "im",
  1111. },
  1112. {
  1113. name: "not subscribed to im",
  1114. events: []string{"presence"},
  1115. record: true,
  1116. channelID: wire.ICBMChannelIM,
  1117. wantEvent: false,
  1118. },
  1119. }
  1120. for _, tt := range tests {
  1121. t.Run(tt.name, func(t *testing.T) {
  1122. sess := &Session{
  1123. Events: tt.events,
  1124. EventQueue: NewEventQueue(10),
  1125. }
  1126. if tt.record {
  1127. sess.RecordSentIM(cookie, msgID)
  1128. }
  1129. sess.handleSNACMessage(wire.SNACMessage{
  1130. Frame: wire.SNACFrame{
  1131. FoodGroup: wire.ICBM,
  1132. SubGroup: wire.ICBMClientErr,
  1133. },
  1134. Body: wire.SNAC_0x04_0x0B_ICBMClientErr{
  1135. Cookie: cookie,
  1136. ChannelID: tt.channelID,
  1137. ScreenName: "Mike Kelly",
  1138. Code: 0x0004,
  1139. },
  1140. })
  1141. events := sess.EventQueue.GetAllEvents()
  1142. if !tt.wantEvent {
  1143. assert.Empty(t, events)
  1144. return
  1145. }
  1146. require.Len(t, events, 1)
  1147. assert.Equal(t, EventTypeClientError, events[0].Type)
  1148. got := events[0].Data.(ClientErrorEvent)
  1149. assert.Equal(t, tt.wantCooki, got.Cookie)
  1150. assert.Equal(t, tt.wantChan, got.Channel)
  1151. // The client keys users by the normalized id and renders the sender's
  1152. // own formatting, so both forms have to survive the translation.
  1153. assert.Equal(t, "mikekelly", got.Source.AimID)
  1154. assert.Equal(t, "Mike Kelly", got.Source.DisplayID)
  1155. })
  1156. }
  1157. }
  1158. func TestSession_RecordSentIMEvictsOldestCookie(t *testing.T) {
  1159. sess := &Session{}
  1160. for i := 0; i <= sentIMCookieLimit; i++ {
  1161. sess.RecordSentIM(uint64(i), fmt.Sprintf("msg-%d", i))
  1162. }
  1163. // The map is capped, so the oldest send is forgotten while the newest and the
  1164. // one that pushed the map over its limit are both still resolvable.
  1165. assert.Equal(t, "", sess.msgIDForCookie(0))
  1166. assert.Equal(t, "msg-1", sess.msgIDForCookie(1))
  1167. assert.Equal(t, fmt.Sprintf("msg-%d", sentIMCookieLimit), sess.msgIDForCookie(uint64(sentIMCookieLimit)))
  1168. assert.Len(t, sess.sentIMs, sentIMCookieLimit)
  1169. // A repeat cookie updates in place rather than consuming another slot.
  1170. sess.RecordSentIM(1, "msg-1-again")
  1171. assert.Equal(t, "msg-1-again", sess.msgIDForCookie(1))
  1172. assert.Len(t, sess.sentIMs, sentIMCookieLimit)
  1173. }
  1174. // A buddy's mood rides along in the capability list of a BuddyArrived, so the
  1175. // presence event has to carry it as a mood icon URL.
  1176. func TestSession_PublishesMoodOnPresence(t *testing.T) {
  1177. newSession := func() *Session {
  1178. return &Session{
  1179. ScreenName: state.DisplayScreenName("me"),
  1180. BaseURL: "http://host",
  1181. Events: []string{"presence"},
  1182. EventQueue: NewEventQueue(10),
  1183. logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
  1184. }
  1185. }
  1186. // arrived delivers a BuddyArrived carrying a raw capabilities TLV value.
  1187. arrived := func(sess *Session, caps []byte, invisible bool) PresenceEvent {
  1188. info := wire.TLVUserInfo{ScreenName: "Mike Kelly"}
  1189. if caps != nil {
  1190. info.Append(wire.NewTLVBE(wire.OServiceUserInfoOscarCaps, caps))
  1191. }
  1192. if invisible {
  1193. info.Append(wire.NewTLVBE(wire.OServiceUserInfoStatus, wire.OServiceUserStatusInvisible))
  1194. }
  1195. sess.handleBuddyArrived(wire.SNACMessage{Body: wire.SNAC_0x03_0x0B_BuddyArrived{TLVUserInfo: info}})
  1196. events := sess.EventQueue.GetAllEvents()
  1197. require.Len(t, events, 1)
  1198. return events[0].Data.(PresenceEvent)
  1199. }
  1200. capBytes := func(caps ...[16]byte) []byte {
  1201. var b []byte
  1202. for _, c := range caps {
  1203. b = append(b, c[:]...)
  1204. }
  1205. return b
  1206. }
  1207. t.Run("a mood capability yields the mood icon URL", func(t *testing.T) {
  1208. got := arrived(newSession(), capBytes(wire.CapXStatusBeer), false)
  1209. assert.Equal(t, "http://host/mood?id="+wire.MoodIconID("0icqmood4"), got.MoodIcon)
  1210. })
  1211. t.Run("a placeholder capability resolves too", func(t *testing.T) {
  1212. got := arrived(newSession(), capBytes(wire.CapMoodOnTheWay), false)
  1213. assert.Equal(t, "http://host/mood?id="+wire.MoodIconID("0icqmood83"), got.MoodIcon)
  1214. })
  1215. t.Run("a shared capability resolves to the canonical mood", func(t *testing.T) {
  1216. // Console is reachable from 0icqmood15 and 0icqmood81; the table's first
  1217. // entry wins, so the client is told the one it labels "gamepad".
  1218. got := arrived(newSession(), capBytes(wire.CapXStatusConsole), false)
  1219. assert.Equal(t, "http://host/mood?id="+wire.MoodIconID("0icqmood81"), got.MoodIcon)
  1220. })
  1221. t.Run("a mood is found after other capabilities", func(t *testing.T) {
  1222. got := arrived(newSession(), capBytes(wire.CapChat, wire.CapXStatusBeer), false)
  1223. assert.Equal(t, "http://host/mood?id="+wire.MoodIconID("0icqmood4"), got.MoodIcon)
  1224. })
  1225. t.Run("capabilities carrying no mood yield no icon", func(t *testing.T) {
  1226. assert.Empty(t, arrived(newSession(), capBytes(wire.CapChat), false).MoodIcon)
  1227. })
  1228. t.Run("no capabilities TLV yields no icon", func(t *testing.T) {
  1229. assert.Empty(t, arrived(newSession(), nil, false).MoodIcon)
  1230. })
  1231. t.Run("a trailing partial capability is ignored", func(t *testing.T) {
  1232. // A truncated final chunk must not be read as a capability, nor panic.
  1233. truncated := append(capBytes(wire.CapXStatusBeer), 0x01, 0x02, 0x03)
  1234. got := arrived(newSession(), truncated, false)
  1235. assert.Equal(t, "http://host/mood?id="+wire.MoodIconID("0icqmood4"), got.MoodIcon)
  1236. })
  1237. t.Run("a partial capability alone yields no icon", func(t *testing.T) {
  1238. assert.Empty(t, arrived(newSession(), []byte{0x01, 0x02, 0x03}, false).MoodIcon)
  1239. })
  1240. t.Run("an invisible buddy shows no mood", func(t *testing.T) {
  1241. // A mood supersedes state on the client, so one here would render the
  1242. // buddy as present instead of offline.
  1243. got := arrived(newSession(), capBytes(wire.CapXStatusBeer), true)
  1244. assert.Equal(t, "offline", got.State)
  1245. assert.Empty(t, got.MoodIcon)
  1246. })
  1247. }