server.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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. )
  14. func NewServer(listeners []string, logger *slog.Logger, handler Handler, apiKeyValidator middleware.APIKeyValidator, sessionManager *state.WebAPISessionManager) *Server {
  15. servers := make([]*http.Server, 0, len(listeners))
  16. authMiddleware := middleware.NewAuthMiddleware(apiKeyValidator, logger)
  17. authHandler := &handlers.AuthHandler{
  18. AuthService: handler.AuthService,
  19. CookieBaker: handler.CookieBaker,
  20. Logger: logger,
  21. }
  22. sessionHandler := &handlers.SessionHandler{
  23. SessionManager: sessionManager,
  24. OSCARAuthService: handler.AuthService,
  25. FeedbagService: handler.FeedbagService,
  26. BuddyListManager: handler.BuddyListManager.(*handlers.BuddyListManager),
  27. Logger: logger,
  28. OServiceService: handler.OServiceService,
  29. }
  30. eventsHandler := &handlers.EventsHandler{
  31. SessionManager: sessionManager,
  32. Logger: logger,
  33. }
  34. presenceHandler := &handlers.PresenceHandler{
  35. SessionManager: sessionManager,
  36. FeedbagService: handler.FeedbagService,
  37. BuddyBroadcaster: handler.BuddyBroadcaster,
  38. LocateService: handler.LocateService,
  39. Logger: logger,
  40. }
  41. buddyListHandler := &handlers.BuddyListHandler{
  42. BuddyListManager: handler.BuddyListManager.(*handlers.BuddyListManager),
  43. Logger: logger,
  44. FeedbagService: handler.FeedbagService,
  45. }
  46. messagingHandler := &handlers.MessagingHandler{
  47. SessionManager: sessionManager,
  48. ICBMService: handler.ICBMService,
  49. LocateService: handler.LocateService,
  50. FeedbagService: handler.FeedbagService,
  51. Logger: logger,
  52. }
  53. preferenceHandler := &handlers.PreferenceHandler{
  54. SessionManager: sessionManager,
  55. FeedbagService: handler.FeedbagService,
  56. Logger: logger,
  57. }
  58. memberDirHandler := &handlers.MemberDirHandler{
  59. DirSearchService: handler.DirSearchService,
  60. LocateService: handler.LocateService,
  61. Logger: logger,
  62. }
  63. oscarBridgeHandler := &handlers.OSCARBridgeHandler{
  64. SessionManager: sessionManager,
  65. OSCARAuthService: handler.AuthService,
  66. CookieBaker: handler.CookieBaker,
  67. Config: handler.OSCARConfig,
  68. Logger: logger,
  69. }
  70. for _, l := range listeners {
  71. mux := http.NewServeMux()
  72. // Exact root only. Pattern "GET /" matches every GET path in Go 1.22+ (prefix /), which
  73. // would steal /getAggregated and other lifestream URLs before stubs/404.
  74. mux.HandleFunc("GET /{$}", handler.GetHelloWorldHandler)
  75. // Authentication endpoint (public - no API key required for user login)
  76. // Using pattern with explicit method for Go 1.22+ routing
  77. mux.HandleFunc("POST /auth/clientLogin", func(w http.ResponseWriter, r *http.Request) {
  78. // Set CORS headers for public endpoint
  79. w.Header().Set("Access-Control-Allow-Origin", "*")
  80. w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
  81. w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  82. authHandler.ClientLogin(w, r)
  83. })
  84. // Handle OPTIONS for CORS preflight
  85. mux.HandleFunc("OPTIONS /auth/clientLogin", func(w http.ResponseWriter, r *http.Request) {
  86. w.Header().Set("Access-Control-Allow-Origin", "*")
  87. w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
  88. w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  89. w.WriteHeader(http.StatusNoContent)
  90. })
  91. mux.HandleFunc("GET /auth/getToken", func(w http.ResponseWriter, r *http.Request) {
  92. w.Header().Set("Access-Control-Allow-Origin", "*")
  93. w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
  94. w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  95. authHandler.GetToken(w, r)
  96. })
  97. mux.HandleFunc("OPTIONS /auth/getToken", func(w http.ResponseWriter, r *http.Request) {
  98. w.Header().Set("Access-Control-Allow-Origin", "*")
  99. w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
  100. w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  101. w.WriteHeader(http.StatusNoContent)
  102. })
  103. // Web AIM navigates the browser here on File > Logout; clear SSO state
  104. // and redirect to the login screen.
  105. mux.HandleFunc("GET /auth/logout", authHandler.Logout)
  106. mux.HandleFunc("GET /_cqr/login/login.psp", authHandler.LoginPSP)
  107. mux.HandleFunc("POST /_cqr/login/login.psp", authHandler.LoginPSP)
  108. // Authenticated Web AIM API endpoints
  109. // SessionInstance management - supports multiple auth methods (k, a, ts+sig_sha256)
  110. mux.Handle("GET /aim/startSession", authMiddleware.AuthenticateFlexible(
  111. authMiddleware.CORSMiddleware(
  112. http.HandlerFunc(sessionHandler.StartSession))))
  113. // End session - uses aimsid for auth, no k required
  114. mux.Handle("GET /aim/endSession", authMiddleware.AuthenticateFlexible(
  115. authMiddleware.CORSMiddleware(
  116. authMiddleware.RequireSession(sessionManager, sessionHandler.EndSession))))
  117. // Event fetching - uses aimsid for auth, no k required
  118. mux.Handle("GET /aim/fetchEvents", authMiddleware.AuthenticateFlexible(
  119. authMiddleware.CORSMiddleware(
  120. authMiddleware.RequireSession(sessionManager, eventsHandler.FetchEvents))))
  121. // Add temp buddy - uses aimsid for auth
  122. mux.Handle("GET /aim/addTempBuddy", authMiddleware.AuthenticateFlexible(
  123. authMiddleware.CORSMiddleware(
  124. authMiddleware.RequireSession(sessionManager, buddyListHandler.AddTempBuddy))))
  125. mux.Handle("GET /aim/removeTempBuddy", authMiddleware.AuthenticateFlexible(
  126. authMiddleware.CORSMiddleware(
  127. authMiddleware.RequireSession(sessionManager, buddyListHandler.RemoveTempBuddy))))
  128. aimStub := &handlers.AimStubHandler{Logger: logger}
  129. aimRoute := func(h http.HandlerFunc) http.Handler {
  130. return authMiddleware.AuthenticateFlexible(
  131. authMiddleware.CORSMiddleware(http.HandlerFunc(h)))
  132. }
  133. mux.Handle("GET /aim/setForwardDomain", aimRoute(aimStub.SetForwardDomain))
  134. mux.Handle("GET /aim/getData", aimRoute(aimStub.GetData))
  135. conversationStub := &handlers.ConversationStubHandler{
  136. SessionManager: sessionManager,
  137. Logger: logger,
  138. }
  139. mux.Handle("GET /conversation/update", aimRoute(conversationStub.Update))
  140. mux.Handle("GET /conversation/close", aimRoute(conversationStub.Close))
  141. mux.Handle("GET /imlog/markRead", aimRoute(conversationStub.MarkRead))
  142. mux.Handle("GET /imlog/fetchStoredIMs", authMiddleware.AuthenticateFlexible(
  143. authMiddleware.CORSMiddleware(
  144. authMiddleware.RequireSession(sessionManager, conversationStub.FetchStoredIMs))))
  145. // Presence and buddy list
  146. // GetPresence supports aimsid-based auth, so we use flexible auth
  147. mux.Handle("GET /presence/get", authMiddleware.AuthenticateFlexible(
  148. authMiddleware.CORSMiddleware(
  149. authMiddleware.RequireSession(sessionManager, presenceHandler.GetPresence))))
  150. buddyListRoute := func(h func(http.ResponseWriter, *http.Request, *state.WebAPISession)) http.Handler {
  151. return authMiddleware.AuthenticateFlexible(
  152. authMiddleware.CORSMiddleware(
  153. authMiddleware.RequireSession(sessionManager, h)))
  154. }
  155. mux.Handle("GET /buddylist/addBuddy", buddyListRoute(buddyListHandler.AddBuddy))
  156. mux.Handle("GET /buddylist/addGroup", buddyListRoute(buddyListHandler.AddGroup))
  157. mux.Handle("GET /buddylist/removeBuddy", buddyListRoute(buddyListHandler.RemoveBuddy))
  158. mux.Handle("GET /buddylist/removeGroup", buddyListRoute(buddyListHandler.RemoveGroup))
  159. mux.Handle("GET /buddylist/renameGroup", buddyListRoute(buddyListHandler.RenameGroup))
  160. mux.Handle("GET /buddylist/moveBuddy", buddyListRoute(buddyListHandler.MoveBuddy))
  161. mux.Handle("GET /buddylist/setBuddyAttribute", buddyListRoute(buddyListHandler.SetBuddyAttribute))
  162. mux.Handle("GET /buddylist/setGroupAttribute", buddyListRoute(buddyListHandler.SetGroupAttribute))
  163. // sendIM supports aimsid-based auth, so we use flexible auth.
  164. // The Web AIM client POSTs the message body (non-IE browsers); IE uses GET.
  165. sendIMHandler := authMiddleware.AuthenticateFlexible(
  166. authMiddleware.CORSMiddleware(
  167. authMiddleware.RequireSession(sessionManager, messagingHandler.SendIM)))
  168. mux.Handle("GET /im/sendIM", sendIMHandler)
  169. mux.Handle("POST /im/sendIM", sendIMHandler)
  170. mux.Handle("GET /im/setTyping", authMiddleware.AuthenticateFlexible(
  171. authMiddleware.CORSMiddleware(
  172. authMiddleware.RequireSession(sessionManager, messagingHandler.SetTyping))))
  173. // SetState only requires aimsid, no k parameter needed
  174. mux.Handle("GET /presence/setState", authMiddleware.AuthenticateFlexible(
  175. authMiddleware.CORSMiddleware(
  176. authMiddleware.RequireSession(sessionManager, presenceHandler.SetState))))
  177. // These presence endpoints support aimsid-based auth where k is not required
  178. mux.Handle("GET /presence/setStatus", authMiddleware.AuthenticateFlexible(
  179. authMiddleware.CORSMiddleware(
  180. authMiddleware.RequireSession(sessionManager, presenceHandler.SetStatus))))
  181. mux.Handle("GET /presence/setProfile", authMiddleware.AuthenticateFlexible(
  182. authMiddleware.CORSMiddleware(
  183. authMiddleware.RequireSession(sessionManager, presenceHandler.SetProfile))))
  184. mux.Handle("GET /presence/getProfile", authMiddleware.AuthenticateFlexible(
  185. authMiddleware.CORSMiddleware(
  186. authMiddleware.RequireSession(sessionManager, presenceHandler.GetProfile))))
  187. mux.HandleFunc("GET /presence/icon", presenceHandler.Icon)
  188. // Member directory search and self directory-info retrieval. Both use
  189. // aimsid-based auth, so we use flexible auth.
  190. mux.Handle("GET /memberDir/search", authMiddleware.AuthenticateFlexible(
  191. authMiddleware.CORSMiddleware(
  192. authMiddleware.RequireSession(sessionManager, memberDirHandler.Search))))
  193. mux.Handle("GET /memberDir/get", authMiddleware.AuthenticateFlexible(
  194. authMiddleware.CORSMiddleware(
  195. authMiddleware.RequireSession(sessionManager, memberDirHandler.Get))))
  196. // These endpoints support aimsid-based auth, so we use a flexible auth approach
  197. mux.Handle("GET /preference/set", authMiddleware.AuthenticateFlexible(
  198. authMiddleware.CORSMiddleware(
  199. authMiddleware.RequireSession(sessionManager, preferenceHandler.SetPreferences))))
  200. mux.Handle("GET /preference/get", authMiddleware.AuthenticateFlexible(
  201. authMiddleware.CORSMiddleware(
  202. authMiddleware.RequireSession(sessionManager, preferenceHandler.GetPreferences))))
  203. mux.Handle("GET /preference/setPermitDeny", authMiddleware.AuthenticateFlexible(
  204. authMiddleware.CORSMiddleware(
  205. authMiddleware.RequireSession(sessionManager, preferenceHandler.SetPermitDeny))))
  206. mux.Handle("GET /preference/getPermitDeny", authMiddleware.AuthenticateFlexible(
  207. authMiddleware.CORSMiddleware(
  208. authMiddleware.RequireSession(sessionManager, preferenceHandler.GetPermitDeny))))
  209. // OSCAR Bridge endpoint
  210. mux.Handle("GET /aim/startOSCARSession", authMiddleware.Authenticate(
  211. authMiddleware.CORSMiddleware(
  212. http.HandlerFunc(oscarBridgeHandler.StartOSCARSession))))
  213. // Expressions endpoint (for buddy icons, etc.)
  214. expressionsHandler := handlers.NewExpressionsHandler(logger)
  215. mux.Handle("GET /expressions/get", authMiddleware.AuthenticateFlexible(
  216. authMiddleware.CORSMiddleware(
  217. http.HandlerFunc(expressionsHandler.Get))))
  218. // Web AIM calls lifestream/* on the API host (e.g. /lifestream/getUserDetails).
  219. lifestreamStub := &handlers.UserInfoStubHandler{Logger: logger}
  220. lifestreamRoute := func(h http.HandlerFunc) http.Handler {
  221. return authMiddleware.AuthenticateFlexible(
  222. authMiddleware.CORSMiddleware(http.HandlerFunc(h)))
  223. }
  224. // getUserDetails returns a minimal AIM identity. Every other lifestream/*
  225. // method is an unimplemented social-feed feature; the subtree catch-all
  226. // acknowledges them with an empty 200 so the client doesn't error.
  227. mux.Handle("GET /lifestream/getUserDetails", lifestreamRoute(lifestreamStub.GetUserDetails))
  228. mux.Handle("GET /lifestream/", lifestreamRoute(lifestreamStub.EmptyOK))
  229. // Unmatched paths (pattern "/" matches anything not covered by routes above).
  230. mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  231. logger.Debug("webapi 404", "method", r.Method, "path", r.URL.Path)
  232. handlers.SendError(w, http.StatusNotFound, "not found")
  233. })
  234. servers = append(servers, &http.Server{
  235. Addr: l,
  236. Handler: middleware.RequestLogger(logger, mux),
  237. })
  238. }
  239. shutdownCtx, shutdownCancel := context.WithCancel(context.Background())
  240. sessionHandler.FnSessCfg = func(sess *state.Session) {
  241. sess.OnSessionClose(func() {
  242. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  243. defer cancel()
  244. if !shuttingDown(shutdownCtx) {
  245. if err := handler.BuddyBroadcaster.BroadcastBuddyDeparted(ctx, sess.IdentScreenName()); err != nil {
  246. logger.ErrorContext(ctx, "error sending buddy departure notifications", "err", err.Error())
  247. }
  248. }
  249. // buddy list must be cleared before session is closed, otherwise
  250. // there will be a race condition that could cause the buddy list
  251. // be prematurely deleted.
  252. if err := handler.BuddyListRegistry.UnregisterBuddyList(ctx, sess.IdentScreenName()); err != nil {
  253. logger.ErrorContext(ctx, "error removing buddy list entry", "err", err.Error())
  254. }
  255. handler.ChatSessionManager.RemoveUserFromAllChats(sess.IdentScreenName())
  256. handler.AuthService.Signout(ctx, sess)
  257. })
  258. }
  259. sessionHandler.FnSessInit = func(instance *state.SessionInstance) func() error {
  260. return func() error {
  261. // make buddy list visible to other users
  262. if err := handler.BuddyListRegistry.RegisterBuddyList(shutdownCtx, instance.IdentScreenName()); err != nil {
  263. return fmt.Errorf("unable to init buddy list: %w", err)
  264. }
  265. // restore warning level from last session
  266. if err := handler.RecalcWarning(shutdownCtx, instance); err != nil {
  267. return fmt.Errorf("failed to recalculate warning level: %w", err)
  268. }
  269. // periodically decay warning level
  270. go handler.LowerWarnLevel(shutdownCtx, instance)
  271. return nil
  272. }
  273. }
  274. sessionHandler.FnInstanceClose = func(instance *state.SessionInstance) func() {
  275. return func() {
  276. if shuttingDown(shutdownCtx) {
  277. return
  278. }
  279. if instance.Session().Invisible() {
  280. if err := handler.BuddyBroadcaster.BroadcastBuddyDeparted(shutdownCtx, instance.IdentScreenName()); err != nil {
  281. logger.ErrorContext(shutdownCtx, "error sending buddy departure notifications", "err", err.Error())
  282. }
  283. } else {
  284. if err := handler.BuddyBroadcaster.BroadcastBuddyArrived(shutdownCtx, instance.IdentScreenName(), instance.Session().TLVUserInfo()); err != nil {
  285. logger.ErrorContext(shutdownCtx, "error sending buddy arrival notifications", "err", err.Error())
  286. }
  287. }
  288. }
  289. }
  290. return &Server{
  291. servers: servers,
  292. logger: logger,
  293. sessionManager: sessionManager,
  294. shutdownCtx: shutdownCtx,
  295. shutdownCancel: shutdownCancel,
  296. }
  297. }
  298. // Server hosts an HTTP endpoint capable of handling AIM-style Kerberos
  299. // authentication. The messages are structured as SNACs transmitted over HTTP.
  300. //
  301. // shutdownCtx bounds the lifetime of the background session reaper: ListenAndServe
  302. // drives it, and Shutdown (or a failed listener) calls shutdownCancel to unwind.
  303. type Server struct {
  304. servers []*http.Server
  305. logger *slog.Logger
  306. sessionManager *state.WebAPISessionManager
  307. shutdownCtx context.Context
  308. shutdownCancel context.CancelFunc
  309. }
  310. func (s *Server) ListenAndServe() error {
  311. if len(s.servers) == 0 {
  312. s.logger.Debug("no webapi listeners defined")
  313. return nil
  314. }
  315. g, ctx := errgroup.WithContext(s.shutdownCtx)
  316. g.Go(func() error {
  317. s.sessionManager.Run(ctx)
  318. return nil
  319. })
  320. for _, server := range s.servers {
  321. g.Go(func() error {
  322. s.logger.Info("starting server", "addr", server.Addr)
  323. if err := server.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
  324. s.shutdownCancel()
  325. return fmt.Errorf("unable to start webapi server: %w", err)
  326. }
  327. return nil
  328. })
  329. }
  330. return g.Wait()
  331. }
  332. func (s *Server) Shutdown(ctx context.Context) error {
  333. s.logger.Debug("Initiating graceful shutdown...")
  334. s.shutdownCancel() // stop the session reaper so ListenAndServe's errgroup can drain
  335. for _, srv := range s.servers {
  336. _ = srv.Shutdown(ctx)
  337. }
  338. s.sessionManager.Shutdown()
  339. s.logger.Info("shutdown complete")
  340. return nil
  341. }
  342. func shuttingDown(ctx context.Context) bool {
  343. select {
  344. case <-ctx.Done():
  345. // server is shutting down, don't send buddy notifications
  346. return true
  347. default:
  348. }
  349. return false
  350. }