server.go 19 KB

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