server.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. package webapi
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "log/slog"
  7. "net/http"
  8. "time"
  9. "golang.org/x/sync/errgroup"
  10. "github.com/mk6i/open-oscar-server/server/webapi/handlers"
  11. "github.com/mk6i/open-oscar-server/server/webapi/middleware"
  12. "github.com/mk6i/open-oscar-server/state"
  13. "github.com/mk6i/open-oscar-server/wire"
  14. )
  15. func NewServer(listeners []string, logger *slog.Logger, handler Handler, apiKeyValidator middleware.APIKeyValidator, sessionManager *state.WebAPISessionManager) *Server {
  16. servers := make([]*http.Server, 0, len(listeners))
  17. authMiddleware := middleware.NewAuthMiddleware(apiKeyValidator, logger)
  18. rateLimiter := handlers.NewRateLimitMiddleware(handler.SNACRateLimits, logger)
  19. authHandler := &handlers.AuthHandler{
  20. AuthService: handler.AuthService,
  21. CookieBaker: handler.CookieBaker,
  22. Logger: logger,
  23. }
  24. sessionHandler := &handlers.SessionHandler{
  25. SessionManager: sessionManager,
  26. OSCARAuthService: handler.AuthService,
  27. FeedbagService: handler.FeedbagService,
  28. BuddyListManager: handler.BuddyListManager.(*handlers.BuddyListManager),
  29. IconSource: handler.IconSource,
  30. Logger: logger,
  31. OServiceService: handler.OServiceService,
  32. SNACRateLimits: handler.SNACRateLimits,
  33. }
  34. eventsHandler := &handlers.EventsHandler{
  35. SessionManager: sessionManager,
  36. Logger: logger,
  37. }
  38. presenceHandler := &handlers.PresenceHandler{
  39. SessionManager: sessionManager,
  40. FeedbagService: handler.FeedbagService,
  41. BuddyBroadcaster: handler.BuddyBroadcaster,
  42. LocateService: handler.LocateService,
  43. IconSource: handler.IconSource,
  44. Logger: logger,
  45. }
  46. buddyListHandler := &handlers.BuddyListHandler{
  47. BuddyListManager: handler.BuddyListManager.(*handlers.BuddyListManager),
  48. Logger: logger,
  49. FeedbagService: handler.FeedbagService,
  50. }
  51. messagingHandler := &handlers.MessagingHandler{
  52. SessionManager: sessionManager,
  53. ICBMService: handler.ICBMService,
  54. LocateService: handler.LocateService,
  55. FeedbagService: handler.FeedbagService,
  56. Logger: logger,
  57. }
  58. preferenceHandler := &handlers.PreferenceHandler{
  59. SessionManager: sessionManager,
  60. FeedbagService: handler.FeedbagService,
  61. Logger: logger,
  62. }
  63. memberDirHandler := &handlers.MemberDirHandler{
  64. DirSearchService: handler.DirSearchService,
  65. LocateService: handler.LocateService,
  66. Logger: logger,
  67. }
  68. oscarBridgeHandler := &handlers.OSCARBridgeHandler{
  69. SessionManager: sessionManager,
  70. OSCARAuthService: handler.AuthService,
  71. CookieBaker: handler.CookieBaker,
  72. Config: handler.OSCARConfig,
  73. Logger: logger,
  74. }
  75. shutdownCtx, shutdownCancel := context.WithCancel(context.Background())
  76. for _, l := range listeners {
  77. mux := http.NewServeMux()
  78. // CORSMiddleware wraps the auth layer rather than the other way around, so
  79. // that responses the auth layer rejects (400 missing key, 403 bad key, 429
  80. // rate limited) still carry Access-Control-Allow-Origin. A browser blocks a
  81. // cross-origin response without that header, and the Web AIM client reads
  82. // the resulting status-0 empty response as a CORS failure and permanently
  83. // switches its whole request pipeline to JSONP.
  84. //
  85. // oscarRoute charges the request against the rate class for (foodGroup,
  86. // subGroup) before the handler runs; sessionRoute and stubRoute reach no
  87. // food group and so are not rate limited here.
  88. oscarRoute := func(foodGroup uint16, subGroup uint16, h handlers.SessionHandlerFunc) http.Handler {
  89. return authMiddleware.CORSMiddleware(
  90. authMiddleware.AuthenticateFlexible(
  91. authMiddleware.RequireSession(sessionManager,
  92. rateLimiter.OSCAR(foodGroup, subGroup)(h))))
  93. }
  94. sessionRoute := func(h handlers.SessionHandlerFunc) http.Handler {
  95. return authMiddleware.CORSMiddleware(
  96. authMiddleware.AuthenticateFlexible(
  97. authMiddleware.RequireSession(sessionManager, h)))
  98. }
  99. stubRoute := func(h http.HandlerFunc) http.Handler {
  100. return authMiddleware.CORSMiddleware(
  101. authMiddleware.AuthenticateFlexible(h))
  102. }
  103. // Exact root only. Pattern "GET /" matches every GET path in Go 1.22+ (prefix /), which
  104. // would steal /getAggregated and other lifestream URLs before stubs/404.
  105. mux.Handle("GET /{$}", http.HandlerFunc(handler.GetHelloWorldHandler))
  106. // Authentication endpoint (public - no API key required for user login)
  107. // Using pattern with explicit method for Go 1.22+ routing.
  108. mux.Handle("POST /auth/clientLogin", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  109. // Set CORS headers for public endpoint
  110. w.Header().Set("Access-Control-Allow-Origin", "*")
  111. w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
  112. w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  113. authHandler.ClientLogin(w, r)
  114. }))
  115. // Handle OPTIONS for CORS preflight
  116. mux.HandleFunc("OPTIONS /auth/clientLogin", func(w http.ResponseWriter, r *http.Request) {
  117. w.Header().Set("Access-Control-Allow-Origin", "*")
  118. w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
  119. w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  120. w.WriteHeader(http.StatusNoContent)
  121. })
  122. mux.Handle("GET /auth/getToken", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  123. w.Header().Set("Access-Control-Allow-Origin", "*")
  124. w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
  125. w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  126. authHandler.GetToken(w, r)
  127. }))
  128. mux.HandleFunc("OPTIONS /auth/getToken", func(w http.ResponseWriter, r *http.Request) {
  129. w.Header().Set("Access-Control-Allow-Origin", "*")
  130. w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
  131. w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  132. w.WriteHeader(http.StatusNoContent)
  133. })
  134. // Web AIM navigates the browser here on File > Logout; clear SSO state
  135. // and redirect to the login screen.
  136. mux.Handle("GET /auth/logout", http.HandlerFunc(authHandler.Logout))
  137. mux.Handle("GET /_cqr/login/login.psp", http.HandlerFunc(authHandler.LoginPSP))
  138. mux.Handle("POST /_cqr/login/login.psp", http.HandlerFunc(authHandler.LoginPSP))
  139. // Authenticated Web AIM API endpoints
  140. // SessionInstance management - supports multiple auth methods (k, a, ts+sig_sha256).
  141. mux.Handle("GET /aim/startSession",
  142. authMiddleware.CORSMiddleware(
  143. authMiddleware.AuthenticateFlexible(
  144. http.HandlerFunc(sessionHandler.StartSession))))
  145. // End session - uses aimsid for auth, no k required
  146. mux.Handle("GET /aim/endSession", sessionRoute(sessionHandler.EndSession))
  147. // Event fetching - uses aimsid for auth, no k required. This is the
  148. // long-poll loop the client runs continuously.
  149. mux.Handle("GET /aim/fetchEvents", sessionRoute(eventsHandler.FetchEvents))
  150. // Temp buddies are session-local rather than feedbag-backed, but they
  151. // are the Web API's equivalent of the BUDDY temp buddy SNACs and are
  152. // charged as such.
  153. mux.Handle("GET /aim/addTempBuddy", oscarRoute(wire.Buddy, wire.BuddyAddTempBuddies, buddyListHandler.AddTempBuddy))
  154. mux.Handle("GET /aim/removeTempBuddy", oscarRoute(wire.Buddy, wire.BuddyDelTempBuddies, buddyListHandler.RemoveTempBuddy))
  155. aimStub := &handlers.AimStubHandler{Logger: logger}
  156. mux.Handle("GET /aim/setForwardDomain", stubRoute(aimStub.SetForwardDomain))
  157. mux.Handle("GET /aim/getData", stubRoute(aimStub.GetData))
  158. mux.Handle("GET /aim/reportAction", stubRoute(aimStub.ReportAction))
  159. conversationStub := &handlers.ConversationStubHandler{
  160. SessionManager: sessionManager,
  161. Logger: logger,
  162. }
  163. mux.Handle("GET /conversation/update", stubRoute(conversationStub.Update))
  164. mux.Handle("GET /conversation/close", stubRoute(conversationStub.Close))
  165. mux.Handle("GET /imlog/markRead", stubRoute(conversationStub.MarkRead))
  166. mux.Handle("GET /imlog/fetchStoredIMs", sessionRoute(conversationStub.FetchStoredIMs))
  167. // Presence and buddy list
  168. // GetPresence supports aimsid-based auth, so we use flexible auth
  169. mux.Handle("GET /presence/get", oscarRoute(wire.Feedbag, wire.FeedbagQuery, presenceHandler.GetPresence))
  170. mux.Handle("GET /buddylist/addBuddy", oscarRoute(wire.Feedbag, wire.FeedbagInsertItem, buddyListHandler.AddBuddy))
  171. mux.Handle("GET /buddylist/addGroup", oscarRoute(wire.Feedbag, wire.FeedbagInsertItem, buddyListHandler.AddGroup))
  172. mux.Handle("GET /buddylist/removeBuddy", oscarRoute(wire.Feedbag, wire.FeedbagDeleteItem, buddyListHandler.RemoveBuddy))
  173. mux.Handle("GET /buddylist/removeGroup", oscarRoute(wire.Feedbag, wire.FeedbagDeleteItem, buddyListHandler.RemoveGroup))
  174. mux.Handle("GET /buddylist/renameGroup", oscarRoute(wire.Feedbag, wire.FeedbagUpdateItem, buddyListHandler.RenameGroup))
  175. mux.Handle("GET /buddylist/moveBuddy", oscarRoute(wire.Feedbag, wire.FeedbagUpdateItem, buddyListHandler.MoveBuddy))
  176. mux.Handle("GET /buddylist/setBuddyAttribute", oscarRoute(wire.Feedbag, wire.FeedbagUpdateItem, buddyListHandler.SetBuddyAttribute))
  177. mux.Handle("GET /buddylist/setGroupAttribute", oscarRoute(wire.Feedbag, wire.FeedbagUpdateItem, buddyListHandler.SetGroupAttribute))
  178. // sendIM supports aimsid-based auth, so we use flexible auth.
  179. // The Web AIM client POSTs the message body (non-IE browsers); IE uses GET.
  180. sendIMHandler := oscarRoute(wire.ICBM, wire.ICBMChannelMsgToHost, messagingHandler.SendIM)
  181. mux.Handle("GET /im/sendIM", sendIMHandler)
  182. mux.Handle("POST /im/sendIM", sendIMHandler)
  183. mux.Handle("GET /im/setTyping", oscarRoute(wire.ICBM, wire.ICBMClientEvent, messagingHandler.SetTyping))
  184. // SetState only requires aimsid, no k parameter needed
  185. mux.Handle("GET /presence/setState", oscarRoute(wire.OService, wire.OServiceSetUserInfoFields, presenceHandler.SetState))
  186. // These presence endpoints support aimsid-based auth where k is not required
  187. mux.Handle("GET /presence/setStatus", oscarRoute(wire.OService, wire.OServiceSetUserInfoFields, presenceHandler.SetStatus))
  188. mux.Handle("GET /presence/setProfile", oscarRoute(wire.Locate, wire.LocateSetInfo, presenceHandler.SetProfile))
  189. mux.Handle("GET /presence/getProfile", oscarRoute(wire.Locate, wire.LocateUserInfoQuery, presenceHandler.GetProfile))
  190. // Unauthenticated, like /expressions/get below: buddy icons load as plain
  191. // <img> sources that carry no aimsid.
  192. mux.Handle("GET /presence/icon", http.HandlerFunc(presenceHandler.Icon))
  193. // Member directory search and self directory-info retrieval. Both use
  194. // aimsid-based auth, so we use flexible auth.
  195. mux.Handle("GET /memberDir/search", oscarRoute(wire.ODir, wire.ODirInfoQuery, memberDirHandler.Search))
  196. mux.Handle("GET /memberDir/get", oscarRoute(wire.Locate, wire.LocateGetDirInfo, memberDirHandler.Get))
  197. mux.Handle("GET /memberDir/update", oscarRoute(wire.Locate, wire.LocateSetDirInfo, memberDirHandler.Update))
  198. // These endpoints support aimsid-based auth, so we use a flexible auth approach
  199. mux.Handle("GET /preference/set", oscarRoute(wire.Feedbag, wire.FeedbagUpdateItem, preferenceHandler.SetPreferences))
  200. mux.Handle("GET /preference/get", oscarRoute(wire.Feedbag, wire.FeedbagQuery, preferenceHandler.GetPreferences))
  201. mux.Handle("GET /preference/setPermitDeny", oscarRoute(wire.Feedbag, wire.FeedbagUpdateItem, preferenceHandler.SetPermitDeny))
  202. mux.Handle("GET /preference/getPermitDeny", oscarRoute(wire.Feedbag, wire.FeedbagQuery, preferenceHandler.GetPermitDeny))
  203. // OSCAR Bridge endpoint. Hands off to a BOS session rather than reaching
  204. // a food group, so there is no OSCAR budget to charge.
  205. mux.Handle("GET /aim/startOSCARSession",
  206. authMiddleware.CORSMiddleware(
  207. authMiddleware.Authenticate(
  208. http.HandlerFunc(oscarBridgeHandler.StartOSCARSession))))
  209. // Expressions endpoint (for buddy icons, etc.).
  210. //
  211. // Unauthenticated, like /presence/icon: the buddyIcon URLs this serves are
  212. // published to the client and loaded as plain <img> sources, which carry
  213. // neither an aimsid nor an API key. Threading a session token through them
  214. // instead would leak it into the DOM and defeat caching, since these URLs
  215. // outlive the session that produced them. Buddy icons are public assets.
  216. expressionsHandler := handlers.NewExpressionsHandler(handler.IconSource, logger)
  217. mux.Handle("GET /expressions/get",
  218. authMiddleware.CORSMiddleware(
  219. http.HandlerFunc(expressionsHandler.Get)))
  220. // Web AIM calls lifestream/* on the API host (e.g. /lifestream/getUserDetails).
  221. lifestreamStub := &handlers.UserInfoStubHandler{Logger: logger}
  222. // getUserDetails returns a minimal AIM identity. Every other lifestream/*
  223. // method is an unimplemented social-feed feature; the subtree catch-all
  224. // acknowledges them with an empty 200 so the client doesn't error.
  225. mux.Handle("GET /lifestream/getUserDetails", stubRoute(lifestreamStub.GetUserDetails))
  226. mux.Handle("GET /lifestream/", stubRoute(lifestreamStub.EmptyOK))
  227. // Go 1.22 patterns are method-exact, so an OPTIONS preflight matches none of
  228. // the "GET /x" routes above and would otherwise fall through to the 404
  229. // handler, failing the preflight. CORSMiddleware answers OPTIONS with a 204
  230. // and the appropriate headers before ever reaching the handler below.
  231. mux.Handle("OPTIONS /", authMiddleware.CORSMiddleware(
  232. http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})))
  233. // Unmatched paths (pattern "/" matches anything not covered by routes above).
  234. //
  235. // Wrapped in CORS: the client probes endpoints this server does not
  236. // implement (/service/getAttributes, /metrics/sendIM), and a 404 without
  237. // Access-Control-Allow-Origin is blocked by the browser rather than read as
  238. // a 404, which latches the client into JSONP for the rest of the session.
  239. mux.Handle("/", authMiddleware.CORSMiddleware(
  240. http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  241. logger.Debug("webapi 404", "method", r.Method, "path", r.URL.Path)
  242. handlers.SendError(w, r, http.StatusNotFound, "not found")
  243. })))
  244. servers = append(servers, &http.Server{
  245. Addr: l,
  246. Handler: middleware.RequestLogger(logger, mux),
  247. })
  248. }
  249. sessionHandler.FnSessCfg = func(sess *state.Session) {
  250. sess.OnSessionClose(func() {
  251. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  252. defer cancel()
  253. if !shuttingDown(shutdownCtx) {
  254. if err := handler.BuddyBroadcaster.BroadcastBuddyDeparted(ctx, sess.IdentScreenName()); err != nil {
  255. logger.ErrorContext(ctx, "error sending buddy departure notifications", "err", err.Error())
  256. }
  257. }
  258. // buddy list must be cleared before session is closed, otherwise
  259. // there will be a race condition that could cause the buddy list
  260. // be prematurely deleted.
  261. if err := handler.BuddyListRegistry.UnregisterBuddyList(ctx, sess.IdentScreenName()); err != nil {
  262. logger.ErrorContext(ctx, "error removing buddy list entry", "err", err.Error())
  263. }
  264. handler.ChatSessionManager.RemoveUserFromAllChats(sess.IdentScreenName())
  265. handler.AuthService.Signout(ctx, sess)
  266. })
  267. }
  268. sessionHandler.FnSessInit = func(instance *state.SessionInstance) func() error {
  269. return func() error {
  270. // make buddy list visible to other users
  271. if err := handler.BuddyListRegistry.RegisterBuddyList(shutdownCtx, instance.IdentScreenName()); err != nil {
  272. return fmt.Errorf("unable to init buddy list: %w", err)
  273. }
  274. // restore warning level from last session
  275. if err := handler.RecalcWarning(shutdownCtx, instance); err != nil {
  276. return fmt.Errorf("failed to recalculate warning level: %w", err)
  277. }
  278. // periodically decay warning level
  279. go handler.LowerWarnLevel(shutdownCtx, instance)
  280. // broadcast rate limit transitions to every instance on the account
  281. go handler.OServiceService.MonitorRateLimits(shutdownCtx, instance.Session())
  282. return nil
  283. }
  284. }
  285. sessionHandler.FnInstanceClose = func(instance *state.SessionInstance) func() {
  286. return func() {
  287. if shuttingDown(shutdownCtx) {
  288. return
  289. }
  290. if instance.Session().Invisible() {
  291. if err := handler.BuddyBroadcaster.BroadcastBuddyDeparted(shutdownCtx, instance.IdentScreenName()); err != nil {
  292. logger.ErrorContext(shutdownCtx, "error sending buddy departure notifications", "err", err.Error())
  293. }
  294. } else {
  295. if err := handler.BuddyBroadcaster.BroadcastBuddyArrived(shutdownCtx, instance.IdentScreenName(), instance.Session().TLVUserInfo()); err != nil {
  296. logger.ErrorContext(shutdownCtx, "error sending buddy arrival notifications", "err", err.Error())
  297. }
  298. }
  299. }
  300. }
  301. return &Server{
  302. servers: servers,
  303. logger: logger,
  304. sessionManager: sessionManager,
  305. shutdownCtx: shutdownCtx,
  306. shutdownCancel: shutdownCancel,
  307. }
  308. }
  309. // Server hosts an HTTP endpoint capable of handling AIM-style Kerberos
  310. // authentication. The messages are structured as SNACs transmitted over HTTP.
  311. //
  312. // shutdownCtx bounds the lifetime of the background session reaper: ListenAndServe
  313. // drives it, and Shutdown (or a failed listener) calls shutdownCancel to unwind.
  314. type Server struct {
  315. servers []*http.Server
  316. logger *slog.Logger
  317. sessionManager *state.WebAPISessionManager
  318. shutdownCtx context.Context
  319. shutdownCancel context.CancelFunc
  320. }
  321. func (s *Server) ListenAndServe() error {
  322. if len(s.servers) == 0 {
  323. s.logger.Debug("no webapi listeners defined")
  324. return nil
  325. }
  326. g, ctx := errgroup.WithContext(s.shutdownCtx)
  327. g.Go(func() error {
  328. s.sessionManager.Run(ctx)
  329. return nil
  330. })
  331. for _, server := range s.servers {
  332. g.Go(func() error {
  333. s.logger.Info("starting server", "addr", server.Addr)
  334. if err := server.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
  335. s.shutdownCancel()
  336. return fmt.Errorf("unable to start webapi server: %w", err)
  337. }
  338. return nil
  339. })
  340. }
  341. return g.Wait()
  342. }
  343. func (s *Server) Shutdown(ctx context.Context) error {
  344. s.logger.Debug("Initiating graceful shutdown...")
  345. s.shutdownCancel() // stop the session reaper so ListenAndServe's errgroup can drain
  346. var errs []error
  347. if err := s.sessionManager.Shutdown(ctx); err != nil {
  348. errs = append(errs, fmt.Errorf("draining webapi sessions: %w", err))
  349. }
  350. for _, srv := range s.servers {
  351. if err := srv.Shutdown(ctx); err != nil {
  352. errs = append(errs, fmt.Errorf("stopping webapi listener %s: %w", srv.Addr, err))
  353. }
  354. }
  355. if err := errors.Join(errs...); err != nil {
  356. s.logger.Error("shutdown incomplete", "err", err.Error())
  357. return err
  358. }
  359. s.logger.Info("shutdown complete")
  360. return nil
  361. }
  362. func shuttingDown(ctx context.Context) bool {
  363. select {
  364. case <-ctx.Done():
  365. // server is shutting down, don't send buddy notifications
  366. return true
  367. default:
  368. }
  369. return false
  370. }